我有下面的代码当我没有关闭ServerSocket语句时,我得到一个错误,说它是资源泄漏但是当我添加close语句Eclipse告诉我代码无法访问时,如何更改代码以关闭while语句之外的套接字?
serverSocket = new ServerSocket(ServerPort);
File incomingFile = new File("testfile.txt");
while (true) {
System.out.println("Waiting For File");
Socket incomingSocket = serverSocket.accept();
byte[] mybytearray = new byte[(int) incomingFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(incomingFile));
bis.read(mybytearray, 0, mybytearray.length);
bis.close();
OutputStream os = incomingSocket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
if (incomingSocket != null) {
incomingSocket.close();
}
}
if(serverSocket != null) {
serverSocket.close();
}
答案 0 :(得分:3)
防止资源泄漏的正确方法是使用try..finally
serverSocket = new ServerSocket(serverPort);
try {
File incomingFile = new File("testfile.txt");
while (true) {
// your code
}
} finally {
serverSocket.close();
}
或使用像这样的try-with-resources
构造
try (serverSocket = new ServerSocket(serverPort)) {
File incomingFile = new File("testfile.txt");
while (true) {
// your code
}
}
代码无法访问的原因是因为while
循环未终止。另请注意,serverSocket
在代码中的那一点不能为null,因为除非抛出异常,否则构造函数必须始终生成新实例。