1

I used the code to insert a string into the file. However, that code only supports to insert at the last line of the file. Could you help me to change it to write a string at the first line of string in android. These strings are seperated by line.separator

For example: Current string in file

aaa
bbb
ccc

With new string is "111" please insert it as

111
aaa
bbb
ccc

This is my code

private void writeTextFile(String filecontent)
{           
        String filepath = Environment.getExternalStorageDirectory().getPath();
        String filename=filepath+"/" +  "/" + "filentxt.txt"    ;   
        FileOutputStream fop = null;
        File file = null;

        try {
            file =new File(filename);
            fop=new FileOutputStream(file,true);
            // if file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            filecontent=filecontent+ System.getProperty ("line.separator");
            // get the content in bytes
            byte[] contentInBytes = filecontent.getBytes();
            fop.write(contentInBytes);
            fop.flush();
            fop.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
}
John
  • 2,838
  • 7
  • 36
  • 65

1 Answers1

1

Use RandomAccessFile to Write at beginning of File

String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" +  "/" + "filentxt.txt"    ;   
RandomAccessFile f = new RandomAccessFile(new File(filename), "rw");
f.seek(0); // to the beginning
f.write("111".getBytes());
f.close();
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37