It's finally
, not finally()
:
try {
//...
} catch(IOException e) {
//...
} finally {
//...
}
顺便说一句,你有一个无限循环:
int c=fr.read();
while(c!=-1) {
fw.write(c);
}
您必须读取循环内的数据才能让它完成:
int c=fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
In the finally
块,你的fr
and fw
无法找到变量,因为它们是在范围内声明的try
堵塞。在外面声明它们:
FileReader fr = null;
FileWriter fw = null;
try {
//...
现在,由于它们是用null
值,你还必须做一个null
关闭它们之前检查:
finally {
if (fr != null) {
fr.close();
}
if (fw != null) {
fw.close();
}
}
And the close
两者的方法都可以抛出IOException
也必须处理:
finally {
if (fr != null) {
try {
fr.close();
} catch(IOException e) {
//...
}
}
if (fw != null) {
try {
fw.close();
} catch(IOException e) {
//...
}
}
}
最后,由于您不想使用大量代码来关闭基本流,因此只需将其移至处理Closeable http://docs.oracle.com/javase/7/docs/api/java/io/Closeable.html(请注意,两者FileReader
and FileWriter
实现该接口):
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
最后,您的代码应该如下所示:
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
,所以上面的代码可以重写为:
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();
}
}
}