8067211: rewrite Utils::fileAsString
authoriignatyev
Tue, 16 Dec 2014 02:13:13 +0300
changeset 28197 0be7e4bd3a59
parent 28196 6ba2bd76ea84
child 28198 1e41fbf783e3
8067211: rewrite Utils::fileAsString Reviewed-by: kvn Contributed-by: tatiana.pivovarova@oracle.com
hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java
--- a/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java	Mon Dec 15 09:36:46 2014 +0100
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java	Tue Dec 16 02:13:13 2014 +0300
@@ -32,6 +32,9 @@
 import java.net.InetAddress;
 import java.net.ServerSocket;
 import java.net.UnknownHostException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -40,6 +43,7 @@
 import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 import sun.misc.Unsafe;
 
 /**
@@ -325,28 +329,15 @@
      * or null if not found.
      * @param filename name of the file to read
      * @return String contents of file, or null if file not found.
+     * @throws  IOException
+     *          if an I/O error occurs reading from the file or a malformed or
+     *          unmappable byte sequence is read
      */
-    public static String fileAsString(String filename) {
-        StringBuilder result = new StringBuilder();
-        try {
-            File file = new File(filename);
-            if (file.exists()) {
-                BufferedReader reader = new BufferedReader(new FileReader(file));
-                while (true) {
-                    String line = reader.readLine();
-                    if (line == null) {
-                        break;
-                    }
-                    result.append(line).append("\n");
-                }
-            } else {
-                // Does not exist:
-                return null;
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-        return result.toString();
+    public static String fileAsString(String filename) throws IOException {
+        Path filePath = Paths.get(filename);
+        return Files.exists(filePath)
+            ? Files.lines(filePath).collect(Collectors.joining(NEW_LINE))
+            : null;
     }
 
     /**