我无法编译该程序。问题出在最后一行" out.close"。请告诉我如何纠正它以及它导致问题的原因。
import java.io.*;
public class Test {
public static void main(String args[]) throws IOException {
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedWriter out = new BufferedWriter(new FileWriter(args[1]));
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
} finally {
out.close();
}
}
}
答案 0 :(得分:8)
你必须在try-finally块之外声明BufferedWriter out变量,因为在try块中声明的变量最终超出了范围,它被称为块作用域。代码应该是:
BufferedWriter out = null;
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
out = new BufferedWriter(new FileWriter(args[1]));
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
} finally {
if (out != null)
out.close();
}
或者正如评论中所述,如果Java版本为7或更高版本,您应该使用try-with-resources:
try(BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedWriter out = new BufferedWriter(new FileWriter(args[1])))
{
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
}
在这种情况下,您无需在finally块中手动关闭它。
答案 1 :(得分:2)
Try with Resources(Java 7+)。在这种情况下,不需要密切的陈述。在try中声明的资源将自动关闭。
try(BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedWriter out = new BufferedWriter(new FileWriter(args[1])))
{
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
}
答案 2 :(得分:1)
您需要在yur out
块之外声明您的try . . . finally
变量。由于try
和finally
是两个不同的范围,因此out
块中未定义finally
。