jdk/test/java/io/OutputStreamWriter/Encode.java
changeset 8559 826c03991926
parent 5506 202f599c92aa
child 9035 1255eb81cc2f
--- a/jdk/test/java/io/OutputStreamWriter/Encode.java	Tue Mar 01 12:03:44 2011 +0000
+++ b/jdk/test/java/io/OutputStreamWriter/Encode.java	Tue Mar 01 15:05:32 2011 -0800
@@ -35,8 +35,9 @@
         new Encode();
     }
 
+    final ServerSocket ss = new ServerSocket(0);
+
     Encode() throws Exception {
-        ss = new ServerSocket(0);
         (new Thread(this)).start();
         String toEncode = "\uD800\uDC00 \uD801\uDC01 ";
         String enc1 = URLEncoder.encode(toEncode, "UTF-8");
@@ -47,27 +48,31 @@
             "/missing.nothtml";
         HttpURLConnection uc =  (HttpURLConnection)new URL(url).openConnection();
         uc.connect();
-        String enc2 = URLEncoder.encode(toEncode, "UTF-8");
-        if (!enc1.equals(enc2))
-            throw new RuntimeException("test failed");
-        uc.disconnect();
+        try {
+            String enc2 = URLEncoder.encode(toEncode, "UTF-8");
+            if (!enc1.equals(enc2)) {
+                System.out.println("test failed");
+                throw new RuntimeException("test failed");
+            }
+        } finally {
+            uc.disconnect();
+        }
     }
 
-    ServerSocket ss;
-
     public void run() {
-        try {
-            Socket s = ss.accept();
-            BufferedReader in = new BufferedReader(
-                new InputStreamReader(s.getInputStream()));
+        try (ServerSocket serv = ss;
+             Socket s = serv.accept();
+             BufferedReader in =
+                 new BufferedReader(new InputStreamReader(s.getInputStream())))
+        {
             String req = in.readLine();
-            PrintStream out = new PrintStream(new BufferedOutputStream(
-                s.getOutputStream()));
-            out.print("HTTP/1.1 403 Forbidden\r\n");
-            out.print("\r\n");
-            out.flush();
-            s.close();
-            ss.close();
+            try (OutputStream os = s.getOutputStream();
+                 BufferedOutputStream bos = new BufferedOutputStream(os);
+                 PrintStream out = new PrintStream(bos))
+            {
+                out.print("HTTP/1.1 403 Forbidden\r\n");
+                out.print("\r\n");
+            }
         } catch (Exception e) {
             e.printStackTrace();
         }