Java的。如何将文本追加到file.txt的顶部 [英] Java. How to append text to top of file.txt

查看:195
本文介绍了Java的。如何将文本追加到file.txt的顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过Java添加文本到文本文件beggining。

I need to add text to beggining of text file via Java.

例如我有一个数据test.txt文件:

For example I have test.txt file with data:

Peter
John
Alice

我需要添加(到文件的顶部):

I need to add(to top of file):

Jennifer 

它应该是:

Jennifer
Peter
John
Alice

我有code的一部分,但它附加数据文件的末尾,我需要它的文本添加到文件的顶部:

I have part of code, but It append data to end of file, I need to make It that added text to top of file:

    public static void irasymas(String irasymai){
        try {
         File file = new File("src/lt/test.txt");

                if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(irasymai+ "\r\n");
            bw.close();
} 
       catch (IOException e) {
        e.printStackTrace();                
        }
    }

我已经试过这一点,但是这只能从文件中删除所有数据,而不是插入任何文本:

I have tried this, but this only deletes all data from file and not insert any text:

public static void main(String[] args) throws IOException {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        ArrayList list = new ArrayList();

        try {
            reader = new BufferedReader(new FileReader("src/lt/test.txt"));
            String tmp;
            while ((tmp = reader.readLine()) != null)
                list.add(tmp);
            OUtil.closeReader(reader);

            list.add(0, "Start Text");
            list.add("End Text");

            writer = new BufferedWriter(new FileWriter("src/lt/test.txt"));
            for (int i = 0; i < list.size(); i++)
                writer.write(list.get(i) + "\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            OUtil.closeReader(reader);
            OUtil.closeWriter(writer);
        }
    }

感谢您的帮助。

推荐答案

您可以使用的的RandomAccessFile 来和征求使用光标到 0号位置求(长位置)方法,开始写了。

You can use RandomAccessFile to and seek the cursor to 0th position using seek(long position) method, before starting to write.

作为<一个解释href=\"http://stackoverflow.com/questions/181408/best-way-to-write-bytes-in-the-middle-of-a-file-in-java\">this螺纹

RandomAccessFile f = new RandomAccessFile(new File("yourFile.txt"), "rw");
f.seek(0); // to the beginning
f.write("Jennifer".getBytes());
f.close();

编辑::由许多意见如下指出,这种解决方案的覆盖的由头文件内容。要完全替代的内容,该文件可能必须的删除的和的重新编写

As pointed out below by many comments, this solution overwrites the file content from beginning. To completely replace the content, the File may have to be deleted and re-written.

这篇关于Java的。如何将文本追加到file.txt的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆