使用try with resources自动关闭IO流

本文详细介绍了Java7引入的try-with-resources语句,如何通过自动关闭实现了AutoCloseable接口的资源,如文件I/O、数据库连接、网络通信和压缩文件处理,以及自定义资源类的使用示例。
摘要由CSDN通过智能技术生成

[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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值