gpt4 book ai didi

java - 无法关闭输出流

转载 作者:行者123 更新时间:2023-12-01 06:38:00 25 4
gpt4 key购买 nike

我无法编译该程序。问题出在最后一行“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();
}
}
}

最佳答案

你必须在try-finally block 之外声明BufferedWriter out变量,因为try block 中声明的变量超出了finally的范围,称为 block 作用域。代码应该是这样的:

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 block 中手动关闭它。

关于java - 无法关闭输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com