简体   繁体   English

使用try-with-resources读取和写入同一文件

[英]Reading and writing to the same file using try-with-resources

I am trying to make a program that receives a specified String , and removes every occurence of this String in a text document. 我正在尝试制作一个接收指定String的程序,并删除此String在文本文档中的所有出现。 The text file that is used to read / write is the same. 用于读取/写入的文本文件是相同的。 The arguments used are received from cmd, in this order: 使用的参数是从cmd接收的,顺序如下:

inputString filename

The program compiles fine, but after running it leaves the original text file blank. 该程序可以很好地编译,但是在运行之后它将原始文本文件留为空白。 If i make a try-catch block for input handling, and a try-catch block for output handling, I am able to read and write to the same file. 如果我将try-catch块用于输入处理,将try-catch块用于输出处理,则可以读取和写入同一文件。 If i use a try-with-resources block, I am able to read a file, and save the output to a different file than the original, with all occurences of inputString from cmd removed. 如果我使用try-with-resources块,则能够读取文件,并将输出保存到与原始文件不同的文件中,并删除了cmd中所有inputString But it seems like I can't read and write to the same file using try-with-resources, and also the input.hasNext() statement returns false when I try to do it this way. 但是似乎我无法使用try-with-resources读取和写入同一文件,而且当我尝试以这种方式执行操作时, input.hasNext()语句也会返回false。

Code example below: 下面的代码示例:

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);
            }
        }

    }
}  

I am suspecting that when I create a new PrintWriter object with the argument filename , the original file is overwritten by a blank file before the while-loop executes. 我怀疑当我使用参数filename创建新的PrintWriter对象时,在执行while-loop之前,原始文件会被空白文件覆盖。 Am i right here? 我在这里吗? Is it possible to read and write to the same file using try-with-resources? 是否可以使用try-with-resources读取和写入同一文件?

From the PrintWriter docs : 从PrintWriter docs

If the file exists then it will be truncated to zero size; 如果文件存在,那么它将被截断为零大小; otherwise, a new file will be created. 否则,将创建一个新文件。

So you are correct, by the time you initialize your PrintWriter , your Scanner has nothing to scan. 因此,在初始化PrintWriterScanner没有要扫描的内容,这是正确的。

I would remove the PrintWriter initialization from the resources initialization block, build your file representation in memory, then replace the file contents in another block (or nest it). 我将从资源初始化块中删除PrintWriter初始化,在内存中构建文件表示形式,然后将文件内容替换到另一个块中(或将其嵌套)。

That is, if the file has a reasonable size for your memory to handle the replacement. 也就是说,如果文件具有合理的内存大小,可以处理替换文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM