Overwrite to file

I am writing a simple function like this:

private static void write(String Swrite) throws IOException { if(!file.exists()) { file.createNewFile(); } FileOutputStream fop=new FileOutputStream(file); if(Swrite!=null) fop.write(Swrite.getBytes()); fop.flush(); fop.close(); } 

Every time I call him, he writes, and then I just get the latest notes that are written. How can I change it so as not to overwrite? The file variable is defined globally as file .

+6
source share
5 answers

In your FileOutputStream constructor FileOutputStream you need to add the boolean append parameter. It will look like this:

 FileOutputStream fop = new FileOutputStream(file, true); 

This tells FileOutputStream that it should add the file instead of clearing and overwriting all of its current data.

+3
source

Use constrctor, which takes the append flag as a parameter.

 FileOutputStream fop=new FileOutputStream(file, true); 
+2
source

you should open the file in append mode for this, by default FileOutputStream opens the file in write mode. And you do not need to check the existence of file , this will be done implicitly by FileOutputStream

 private static void write(String Swrite) throws IOException { FileOutputStream fop=new FileOutputStream(file, true); if(Swrite!=null) fop.write(Swrite.getBytes()); fop.flush(); fop.close(); } 
+1
source

Try RandomAccessFile if you are trying to write with some byte offsets.

0
source

Constructor for towing parameters. And this is redundant:

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

The designer will do it for you.

0
source

Source: https://habr.com/ru/post/903647/


All Articles