【发布时间】:2021-07-29 21:43:40
【问题描述】:
所以,我只是想创建一个程序来将内容从一个文件(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-resources,您需要自己在文件处理程序上调用
close()。 Try-with-resources 更好:坚持下去。 -
@TedHopp 没有显示错误... source2.txt 将只是空白...我认为放置空白输出没有意义。
-
@khelwood 我只是想知道 fileReader 在 try 块之外但不是 fileWriter 有什么作用
-
@SomethingNice 大概是因为您没有关闭文件写入器,并且您尝试写入的一些内容仍然被缓存。
标签: java file filereader file-handling filewriter