目录标题
[Q&A] try with resources 作用
在传统的 try-catch-finally
结构中,开发人员需要手动关闭这些资源以防止资源泄露, Java 7 引入了 try-with-resources
语句,它简化了对实现了 java.lang.AutoCloseable
接口的资源(如文件、输入/输出流等)的管理,系统会在 try 块结束时自动关闭它们。
使用样例:使用 InputStream 读取文件内容
try (InputStream is = new FileInputStream("file.txt")) {
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
// 处理读取到的数据...
}
} catch (IOException e) {
e.printStackTrace();
}
使用样例:使用 BufferedReader 读取文件内容
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
使用样例:使用多个资源:
try (
InputStream is = new FileInputStream("input.jpg");
OutputStream os = new FileOutputStream("output.jpg");
) {
byte[] buffer = new byte[4096];
int read;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
使用样例:资源类实现自定义关闭逻辑
class CustomResource implements AutoCloseable {
public void doSomething() {
// 执行操作...
}
@Override
public void close() throws Exception {
// 在此处执行清理或关闭资源的操作
System.out.println("Closing the custom resource...");
}
}
try (CustomResource resource = new CustomResource()) {
resource.doSomething();
} catch (Exception e) {
e.printStackTrace();
}
使用样例:使用 Connection 和 Statement 进行数据库操作
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement()) {
String sql = "SELECT id, name, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
使用样例:使用 Socket 进行网络通信
try (Socket socket = new Socket(HOST, PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
out.println(requestMessage);
String responseLine;
while ((responseLine = in.readLine()) != null) {
System.out.println(responseLine);
}
} catch (IOException e) {
e.printStackTrace();
}
使用样例:使用 ZipFile 处理压缩文件
try (ZipFile zipFile = new ZipFile("archive.zip")) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String entryName = entry.getName();
if (!entry.isDirectory()) {
try (InputStream inputStream = zipFile.getInputStream(entry)) {
// 读取并处理每个条目的内容...
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
// 处理读取到的字节数据...
}
} catch (IOException e) {
System.err.println("Error reading entry: " + entryName);
e.printStackTrace();
}
}
}
} catch (IOException e) {
System.err.println("Error opening or reading the zip file.");
e.printStackTrace();
}
使用样例:使用 Files.lines() 方法读取文本文件
try (Stream<String> lines = Files.lines(Paths.get("input.txt"), StandardCharsets.UTF_8)) {
lines.forEach(System.out::println);
} catch (IOException e) {
System.err.println("Error reading from the file.");
e.printStackTrace();
}
参考
[Ref] spring multipartfile getinputstream close
[Ref] The try-with-resources Statement oracle docs