为什么我不能在使用资源的 Try 之外编写 FileWriter?

Why can't I write FileWriter outside of Try with resources?

所以,我只是想创建一个程序来将内容从一个文件 (source1) 复制到另一个文件 (source2) 并将其转换为小写...在这样做的同时我想出了如下代码:

        try(FileWriter fr=new FileWriter("Source1.txt")){
            String str="UPPER CASE";
            fr.write(str);
        }


        File file=new File("Source1.txt");
        //FileReader fr=new FileReader("Source1.txt"); // (1)
        //FileWriter f2=new FileWriter("Source2.txt"); // (2)

        try(FileReader fr=new FileReader("Source1.txt");FileWriter f2=new FileWriter("Source2.txt")){ //If i remove 
//file Reader from here and uncomment (1) the code works fine but if i do so with FileWriter (Remove
//fileWriter from here and uncomment (2)) I can't copy the contents of the file (No error is shown... the code executes but Source2.txt just comes out as blank file.


            char x[]=new char[(int)file.length()];
            fr.read(x);
            String str=new String(x);
            System.out.println(str);
            String st=str.toLowerCase();
            f2.write(st);


        }

代码没有问题,但我只是想知道为什么它会这样工作(请阅读代码中的注释)?

如果您不使用 try-with-resource 您必须自己关闭资源。
这可能是将任何缓存数据写入流(刷新)所必需的,例如写入文件;释放系统资源也很好。


try (var resource = new Resource()) {
    // statements
}

基本上(忽略错误 handling/exceptions)等同于:

var resource = new Resource();
// statements
resource.close();

或(好一点)

var resource = new Resource();
try {
    // statements
} finally {
    resource.close();
}

如果添加了错误处理,这可能会变得有些复杂 - 所以最好使用 try-with-resource(至少它使代码更容易 read/understand/maintain)。

如果 writer 用完了 try-with-resources,您需要注意使用

刷新和关闭 writer
f2.flush()
f2.close()

flush() 刷新流。如果流已将来自各种 write() 方法的任何字符保存在缓冲区中,它会立即将它们写入预期的目的地。

Try-with-resources 隐含地做同样的事情。