I am making a simple browser for school and I am trying to make the favorites. This code here adds a favorite to a file(so I can keep it after the app is closed) and displays it
to write at first position i.e. prepend then u need to use this
private void writeToFile(Context context,String data){
try{
String path=context.getFilesDir().getAbsolutePath();
File file = new File(path + File.separator + fileName);
RandomAccessFile rf = new RandomAccessFile(file,"rws");
file.getParentFile().mkdirs();
Log.d("creating file path",path);
byte[] text = new byte[(int) file.length()];
rf.readFully(text);
rf.seek(0);
rf.writeBytes(data);
rf.write(text);
Log.d("write","writing file...");
rf.close();
}catch(Exception e){e.printStackTrace(); Log.d("caught", "data wititng fail");}
}
and if u want to append use this
private void writeToFile(Context context,String data){
try{
String path=context.getFilesDir().getAbsolutePath();
File file = new File(path + File.separator + fileName);
RandomAccessFile rf = new RandomAccessFile(file,"rws");
file.getParentFile().mkdirs();
Log.d("creating file path",path);
byte[] text = new byte[(int) file.length()];
rf.readFully(text);
rf.seek(0);
rf.write(text);
rf.writeBytes(data);
Log.d("write","writing file...");
rf.close();
}catch(Exception e){e.printStackTrace(); Log.d("caught", "data wititng fail");}
}
or u can open file in MODE_APPEND mode.. to open file in append mode change to this OutputStreamWriter out=new OutputStreamWriter(openFileOutput(fileName,true));