Bläddra i källkod

Close resources properly for java tests and examples.

liujisi@google.com 14 år sedan
förälder
incheckning
3239fec94c

+ 10 - 4
examples/AddPerson.java

@@ -70,8 +70,11 @@ class AddPerson {
     // Read the existing address book.
     try {
       FileInputStream input = new FileInputStream(args[0]);
-      addressBook.mergeFrom(input);
-      input.close();
+      try {
+        addressBook.mergeFrom(input);
+      } finally {
+        try { input.close(); } catch (Throwable ignore) {}
+      }
     } catch (FileNotFoundException e) {
       System.out.println(args[0] + ": File not found.  Creating a new file.");
     }
@@ -83,7 +86,10 @@ class AddPerson {
 
     // Write the new address book back to disk.
     FileOutputStream output = new FileOutputStream(args[0]);
-    addressBook.build().writeTo(output);
-    output.close();
+    try {
+      addressBook.build().writeTo(output);
+    } finally {
+      output.close();
+    }
   }
 }

+ 10 - 4
java/src/test/java/com/google/protobuf/GeneratedMessageTest.java

@@ -775,8 +775,11 @@ public class GeneratedMessageTest extends TestCase {
     TestUtil.setAllFields(builder);
     TestAllTypes expected = builder.build();
     ObjectOutputStream out = new ObjectOutputStream(baos);
-    out.writeObject(expected);
-    out.close();
+    try {
+      out.writeObject(expected);
+    } finally {
+      out.close();
+    }
     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
     ObjectInputStream in = new ObjectInputStream(bais);
     TestAllTypes actual = (TestAllTypes) in.readObject();
@@ -788,8 +791,11 @@ public class GeneratedMessageTest extends TestCase {
     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
     TestAllTypes expected = builder.buildPartial();
     ObjectOutputStream out = new ObjectOutputStream(baos);
-    out.writeObject(expected);
-    out.close();
+    try {
+      out.writeObject(expected);
+    } finally {
+      out.close();
+    }
     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
     ObjectInputStream in = new ObjectInputStream(bais);
     TestAllTypes actual = (TestAllTypes) in.readObject();

+ 5 - 2
java/src/test/java/com/google/protobuf/LiteTest.java

@@ -129,8 +129,11 @@ public class LiteTest extends TestCase {
                           TestAllTypesLite.NestedMessage.newBuilder().setBb(7))
                       .build();
     ObjectOutputStream out = new ObjectOutputStream(baos);
-    out.writeObject(expected);
-    out.close();
+    try {
+      out.writeObject(expected);
+    } finally {
+      out.close();
+    }
     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
     ObjectInputStream in = new ObjectInputStream(bais);
     TestAllTypesLite actual = (TestAllTypesLite) in.readObject();