Java 关闭流的方法有以下几种:
使用 try-finally 语句块,在 finally 块中关闭流。这是最常见的关闭流的方式,确保在程序执行完后,流一定会被关闭,避免资源泄漏。InputStream is = null;try { is = new FileInputStream("file.txt"); // 使用流进行读取操作} catch (IOException e) { e.printStackTrace();} finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } }}使用 try-with-resources 语句,在 try 块中创建流对象,并在括号中声明流对象,当 try 块结束时,自动关闭流。try (InputStream is = new FileInputStream("file.txt")) { // 使用流进行读取操作} catch (IOException e) { e.printStackTrace();}使用 try-with-resources 语句,同样在括号中声明流对象,但是可以声明多个流对象,用分号隔开。try (InputStream is = new FileInputStream("file.txt"); OutputStream os = new FileOutputStream("output.txt")) { // 使用流进行读写操作} catch (IOException e) { e.printStackTrace();}在 Java 7 及以上版本中,推荐使用 try-with-resources 语句来关闭流,它简化了代码,并且可以确保流一定会被关闭,避免了忘记关闭流的问题。

