Java try-with-resources 语句在编译时被报告为错误
Java try-with-resources statements were reproted as error at compile time
核心 Java 第二卷高级功能 一书中的一个示例使用了 try-with-resources 语句作为一个简单的回显服务器程序。但是,当我编译程序时,编译器报告了下面程序代码后显示的错误。谢谢你的帮助。
程序代码:
/**
* Listing 3.3 server/EchoServer.java
*/
package server;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* This pgoram implements a simple server
* that listens to port 8189 and echoes
* back all client input.
* @version 1.21 2012-05-19
* @author Cay Horstmann
*/
public class EchoServer {
public static void main(String[] args) {
// establish server socket
try (ServerSocket s = new ServerSocket(8189)) {
// wait for client connection
try (Socket incoming = s.accept()) {
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
try (Scanner in = new Scanner(inStream)) {
PrintWriter out = new PrintWriter(outStream, true /*autoFlush*/);
out.println("Heloo! Enter BYE to exit");
// echo client input
boolean done = false;
while (!done && in.hasNext()) {
String line = in.nextLine();
out.println("Echo: " + line);
if (line.trim().toUpperCase().equals("BYE"))
done = true;
}
}
}
}
}
}
编译器报告的错误信息:
正如错误所说
try-with-resources 会自动关闭您在块末尾的 try(...)
中声明的资源,但它不会为您自动处理异常。
所以你要么需要:
- 写入
catch
块以处理 IOException
s
- 声明方法 (
main
) 抛出这些异常。
核心 Java 第二卷高级功能 一书中的一个示例使用了 try-with-resources 语句作为一个简单的回显服务器程序。但是,当我编译程序时,编译器报告了下面程序代码后显示的错误。谢谢你的帮助。
程序代码:
/**
* Listing 3.3 server/EchoServer.java
*/
package server;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* This pgoram implements a simple server
* that listens to port 8189 and echoes
* back all client input.
* @version 1.21 2012-05-19
* @author Cay Horstmann
*/
public class EchoServer {
public static void main(String[] args) {
// establish server socket
try (ServerSocket s = new ServerSocket(8189)) {
// wait for client connection
try (Socket incoming = s.accept()) {
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
try (Scanner in = new Scanner(inStream)) {
PrintWriter out = new PrintWriter(outStream, true /*autoFlush*/);
out.println("Heloo! Enter BYE to exit");
// echo client input
boolean done = false;
while (!done && in.hasNext()) {
String line = in.nextLine();
out.println("Echo: " + line);
if (line.trim().toUpperCase().equals("BYE"))
done = true;
}
}
}
}
}
}
编译器报告的错误信息:
正如错误所说
try-with-resources 会自动关闭您在块末尾的 try(...)
中声明的资源,但它不会为您自动处理异常。
所以你要么需要:
- 写入
catch
块以处理IOException
s - 声明方法 (
main
) 抛出这些异常。