I am trying to clear the contents of a file I made in java. The file is created by a PrintWriter call. I read here that one can use RandomAccessFile to do so, and read somewhere else that this is in fact better to use than calling a new PrintWriter and immediately closing it to overwrite the file with a blank one.
However, using the RandomAccessFile to clear the file seems to be adding a string of null characters to the file (or perhaps it is the PrintWriter?) It only occurs if more text is added.
PrintWriter writer = new PrintWriter("temp","UTF-8");
while (condition) {
writer.println("Example text");
if (clearCondition) {
writer.flush();
new RandomAccessFile("temp","rw").setLength(0);
// Although the solution in the link above did not include ',"rw"'
// My compiler would not accept without a second parameter
writer.println("Text to be written onto the first line of temp file");
}
}
writer.close();
Running the equivalent of the above code is giving my temp file the contents:
^@^@^@^@^@^@^@^@^@^@^@^@^@Text to be written onto the first line of temp file
The number of null characters is equal to the number of characters erased (including newline characters). If no new text is added to the file, it is completely blank.
NOTE: writer needs to be able to write "Example Text" to the file again after the file is cleared. The clearCondition does not mean that the while loop gets broken.
EDIT: I have no idea what caused those null characters. I realized I am stupid and there was no need to have a temp file, just a temp String with all the data that would later be written to a file. Strings are super easy to reset with = ""; Thanks for all the suggestions