Clear contents of a file in Java using RandomAccessFile -


i trying clear contents of file made in java. file created printwriter call. read here 1 can use randomaccessfile so, , read somewhere else in fact better use calling new printwriter , closing overwrite file blank one.

however, using randomaccessfile not working, , don't understand why. here basic outline of code.

printwriter writer = new printwriter("temp","utf-8");  while (condition) { writer.println("example text");  if (clearcondition) { new randomaccessfile("temp","rw").setlength(0);       //  although solution in link above did not include ',"rw"'       //  compiler not accept without second parameter writer.println("text written onto first line of temp file"); } } writer.close(); 

running equivalent of above code giving temp file contents:
(lets imagine program looped twice before clearcondition met)

example text example text text written onto first line of temp file 



note: writer needs able write "example text" file again after file cleared. clearcondition not mean while loop gets broken.

you want either flush printwriter make sure changes in buffer written out first, before set randomaccessfile's length 0, or close , re-open new printwriter write last line (text written...). preferably former:

if (clearcondition) { writer.flush(); new randomaccessfile("temp","rw").setlength(0); 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -