[英]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.