我一直在看Oracle教程网站学习基本的套接字编程。我试图在eclipse上上传示例,但当我试图编译时,括号所在的语法有错误。为什么会发生这种情况?谢谢。
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
为什么会发生这种情况?
您正在尝试"尝试使用资源"。这需要Java 7或更高版本。请确保您的eclipse项目也设置为Java 7,而不仅仅是本地命令行JDK。
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html