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

时间:2015-01-17 07:25:01

标签: java

我有简单的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");
            }
        }
    }
}

}

1 个答案:

答案 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'
}