gpt4 book ai didi

java - 我对嵌套 try-with-resource 的使用是否正确?

转载 作者:搜寻专家 更新时间:2023-10-31 20:27:46 25 4
gpt4 key购买 nike

我有一个简单的 TCP 服务器,它打印客户端发送的消息。我正在尝试修改它以使用 try-with-resource 功能。在我的示例中使用嵌套的 try-with-resource 语句是否正确?

public static void main(String args[]) throws IOException {
String receivedMessage;

try (ServerSocket serverSocket = new ServerSocket(777)) {
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected");
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
while ((receivedMessage = in.readLine()) != null) {
System.out.println(receivedMessage);
}
System.out.println("Client disconnected");
}
}
}
}

最佳答案

是的,你的例子是正确的。

资源尝试 try block 可以独立,因为它有一个隐式 finally堵塞;而传统的 try block 后面必须跟一个 catch block 和/或 finally block 。

因此,您的示例代码等同于以下内容(除了资源变量在其各自 try block 的范围之外可见):

        final ServerSocket serverSocket = new ServerSocket(777);
try {
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected");
final BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
try {
while ((receivedMessage = in.readLine()) != null) {
System.out.println(receivedMessage);
}
System.out.println("Client disconnected");
} finally {
in.close();
}
}
} finally {
serverSocket.close();
}

我会建议您将这两个资源放在同一个 try block 中,除非在您的情况下不起作用,因为有必要调用 accept()在请求其 inputStream() 之前在 serverSocket 上.

但是,在您的代码示例中仍然有适当的机会将多个资源放入您的第二次 try-with-resources 中:

try (Reader stream = new InputStreamReader(socket.getInputStream());
BufferedReader in = new BufferedReader(stream)) {
// do stuff, still preferring to use 'in' here rather than 'stream'
}

关于java - 我对嵌套 try-with-resource 的使用是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27997244/

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