Java close method: Usage & Best Examples
In Java, the close method is typically used to release resources such as files, network connections, and database connections. Closing resources is done to free up resources, prevent resource leaks, and avoid system performance issues.
The close method is typically used within a try-with-resources statement to ensure that resources are automatically closed after they are used. For example:
try (FileInputStream fis = new FileInputStream("file.txt")) {
// 读取文件内容
} catch (IOException e) {
e.printStackTrace();
}
In the code above, the FileInputStream will automatically close after the try block is executed, without needing to manually call the close method.
If you do not use the try-with-resources statement, you can manually call the close method to close the resource, as shown below:
FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
// 读取文件内容
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this situation, it is necessary to manually call the close method in the finally block to close the resource.