将自动资源管理与try-with-resources语句一起使用。
import java.io.BufferedOutputStream; /* n o w j a v a . c o m 提 供 */ import java.io.DataOutputStream; import java.io.FileOutputStream; public class Main { public static void main(String[] args) { try (FileOutputStream fos = new FileOutputStream("out.log"); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos)) { dos.writeUTF("This is being written"); // If an exception occurs here, resources will be handled correctly/** nowjava.com 提供 **/