簡體   English   中英

使用 RandomAccessFile 清除 Java 中文件的內容

[英]Clear contents of a file in Java using RandomAccessFile

我正在嘗試清除我在 java 中創建的文件的內容。 該文件由 PrintWriter 調用創建。 在這里讀到可以使用 RandomAccessFile 來這樣做,並在其他地方讀到這實際上比調用新的 PrintWriter 並立即關閉它以用空白文件覆蓋文件更好。

但是,使用 RandomAccessFile 不起作用,我不明白為什么。 這是我的代碼的基本輪廓。

PrintWriter writer = new PrintWriter("temp","UTF-8");

while (condition) {
writer.println("Example text");

if (clearCondition) {
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();

運行與上述代碼等效的代碼是為我的臨時文件提供內容:
(假設程序在滿足 clearCondition 之前循環了兩次)

Example Text
Example Text
Text to be written onto the first line of temp file



注意:在清除文件后,writer 需要能夠再次將“示例文本”寫入文件。 clearCondition 並不意味着 while 循環被破壞。

在將RandomAccessFile的長度設置為 0 之前,您想要刷新PrintWriter以確保首先寫出其緩沖區中的更改,或者關閉它並重新打開一個新的PrintWriter以寫入最后一行(文本為書面...)。 最好是前者:

if (clearCondition) {
writer.flush();
new RandomAccessFile("temp","rw").setLength(0);

如果同時打開文件兩次有效,你會很幸運。 它沒有被指定為 Java 工作。

您應該做的是關閉 PrintWriter 並打開一個不帶 'append' 參數或將 'append' 設置為 'false' 的新打印機。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM