Clear contents of a file in Java using RandomAccessFile

后端 未结 2 1805
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 12:40

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 somewhe

相关标签:
2条回答
  • 2021-01-26 13:30

    You'll be lucky if opening the file twice at the same time works. It isn't specified to work by Java.

    What you should do is close the PrintWriter and open a new one without the 'append' parameter, or with 'append' set to 'false'.

    0 讨论(0)
  • 2021-01-26 13:32

    You want to either flush the PrintWriter to make sure the changes in its buffer are written out first, before you set the RandomAccessFile's length to 0, or close it and re-open a new PrintWriter to write the last line (Text to be written...). Preferably the former:

    if (clearCondition) {
    writer.flush();
    new RandomAccessFile("temp","rw").setLength(0);
    
    0 讨论(0)
提交回复
热议问题