Writing more than one String to a file without deleting the first one ANDROID favorites for browser

后端 未结 1 1230
粉色の甜心
粉色の甜心 2021-01-24 04:56

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

相关标签:
1条回答
  • 2021-01-24 05:33

    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));

    0 讨论(0)
提交回复
热议问题