我有简单的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");
}
}
}
}
}
答案 0 :(得分:0)
是的,你的例子是正确的。
try-with-resources try
块可以独立存在,因为它具有隐式finally
块;而传统的try
块需要跟随catch
块和/或finally
块。
因此,您的示例代码等效于以下内容(除了资源变量在各自的try块范围之外可见):
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块中,除非你的情况不起作用,因为在询问accept()
之前需要在serverSocket上调用inputStream()
。 / p>
但是,您的代码示例中仍有适当的机会将多个资源放入您的第二个资源尝试中:
try (Reader stream = new InputStreamReader(socket.getInputStream());
BufferedReader in = new BufferedReader(stream)) {
// do stuff, still preferring to use 'in' here rather than 'stream'
}