[英]Reading and writing to the same file using try-with-resources
我正在嘗試制作一個接收指定String
的程序,並刪除此String
在文本文檔中的所有出現。 用於讀取/寫入的文本文件是相同的。 使用的參數是從cmd接收的,順序如下:
inputString filename
該程序可以很好地編譯,但是在運行之后它將原始文本文件留為空白。 如果我將try-catch塊用於輸入處理,將try-catch塊用於輸出處理,則可以讀取和寫入同一文件。 如果我使用try-with-resources塊,則能夠讀取文件,並將輸出保存到與原始文件不同的文件中,並刪除了cmd中所有inputString
。 但是似乎我無法使用try-with-resources讀取和寫入同一文件,而且當我嘗試以這種方式執行操作時, input.hasNext()
語句也會返回false。
下面的代碼示例:
package ch12;
import java.io.*;
import java.util.*;
public class Chapter_12_E11_RemoveText {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Usage java ch12.Chapter_12_E11_RemoveText inputString filename");
System.exit(1);
}
File filename = new File(args[1]);
if (!filename.exists()) {
System.out.println("Target file " + args[1] + " does not exist");
System.exit(2);
}
try (
Scanner input = new Scanner(filename);
PrintWriter output = new PrintWriter(filename);
) {
System.out.println("hasNext() is " + input.hasNext());
System.out.println("hasNextLine() is " + input.hasNextLine());
while (input.hasNext()) {
String s1 = input.nextLine();
System.out.println("String fetched from input.nextLine() " + s1);
System.out.println("Attemping to replace all words equal to " + args[0] + " with \"\"");
String s2 = s1.replaceAll(args[0], "");
output.println(s2);
}
}
}
}
我懷疑當我使用參數filename
創建新的PrintWriter
對象時,在執行while-loop
之前,原始文件會被空白文件覆蓋。 我在這里嗎? 是否可以使用try-with-resources讀取和寫入同一文件?
從PrintWriter docs :
如果文件存在,那么它將被截斷為零大小; 否則,將創建一個新文件。
因此,在初始化PrintWriter
, Scanner
沒有要掃描的內容,這是正確的。
我將從資源初始化塊中刪除PrintWriter
初始化,在內存中構建文件表示形式,然后將文件內容替換到另一個塊中(或將其嵌套)。
也就是說,如果文件具有合理的內存大小,可以處理替換文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.