Java. How to append text to top of file.txt [duplicate]

别说谁变了你拦得住时间么 提交于 2019-11-27 20:30:28
sanbhat

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

As explained in this thread

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

Edit: 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.

File mFile = new File("src/lt/test.txt");
FileInputStream fis = new FileInputStream(mFile);
BufferedReader br = new BufferedReader(fis);
String result = "";
String line = "";
while( (line = br.readLine()) != null){
 result = result + line; 
}

result = "Jennifer" + result;

mFile.delete();
FileOutputStream fos = new FileOutputStream(mFile);
fos.write(result.getBytes());
fos.flush();

The idea is read it all, add the string in the front. Delete old file. Create the new file with eited String.

Joarder Kamal

The below code worked for me. Again it will obviously replace the bytes at the beginning of the file. If you can certain how many bytes of replacement will be done in advance then you can use this. Otherwise, follow the earlier answers or take a look at here Writing in the beginning of a text file Java

    String str = "Jennifer";  
    byte data[] = str.getBytes();       

    try {                           
            RandomAccessFile f = new RandomAccessFile(new File("src/lt/test.txt"), "rw");
            f.getChannel().position(0);         
            f.write(data);
            f.close();
    } catch (IOException e) {       
            e.printStackTrace();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!