更新时间:2023-01-30 20:09:38
它是最后
,而不是 finally()
:
try {
//...
} catch(IOException e) {
//...
} finally {
//...
}
顺便说一下,你有一个无限循环:
By the way, you have an endless loop there:
int c=fr.read();
while(c!=-1) {
fw.write(c);
}
您必须读取循环内的数据才能完成:
You must read the data inside the loop in order to let it finish:
int c=fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
在 finally
阻止,您的 fr
和 fw
变量无法找到,因为它们是在尝试阻止。在外面声明它们:
In the finally
block, your fr
and fw
variables can't be found since they're declared in the scope of the try
block. Declare them outside:
FileReader fr = null;
FileWriter fw = null;
try {
//...
现在,因为它们已初始化使用 null
值,您还必须在关闭它们之前执行 null
检查:
Now, since they are initialized with null
value, you must also do a null
check before closing them:
finally {
if (fr != null) {
fr.close();
}
if (fw != null) {
fw.close();
}
}
关闭两者上的code>方法都可以抛出必须处理的
IOException
:
And the close
method on both can throw IOException
that must be handled as well:
finally {
if (fr != null) {
try {
fr.close();
} catch(IOException e) {
//...
}
}
if (fw != null) {
try {
fw.close();
} catch(IOException e) {
//...
}
}
}
最后,由于您不希望有大量代码来关闭基本流,只需将其移动到处理 可关闭
(请注意, FileReader
和 FileWriter
都实现了此接口):
In the end, since you don't want to have a lot of code to close a basic stream, just move it into a method that handles a Closeable
(note that both FileReader
and FileWriter
implements this interface):
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
最后,您的代码应如下所示:
In the end, your code should look like:
import java.io.*;
class FileDemo {
public static void main(String args[]) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("1.txt");
fw = new FileWriter("2.txt");
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
}
从Java 7开始,我们有 try-with-resources
,因此可以重写上面的代码喜欢:
Since Java 7, we have try-with-resources
, so code above could be rewritten like:
import java.io.*;
class FileDemo {
public static void main(String args[]) {
//this will close the resources automatically
//even if an exception rises
try (FileReader fr = new FileReader("1.txt");
FileWriter fw = new FileWriter("2.txt")) {
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}