1 package org.testng.reporters; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.Closeable; 6 import java.io.File; 7 import java.io.FileInputStream; 8 import java.io.FileOutputStream; 9 import java.io.FileWriter; 10 import java.io.IOException; 11 import java.io.InputStream; 12 import java.io.InputStreamReader; 13 import java.io.OutputStream; 14 import java.io.Reader; 15 import java.io.StringWriter; 16 import java.io.Writer; 17 18 public class Files { 19 readFile(File f)20 public static String readFile(File f) throws IOException { 21 try (InputStream is = new FileInputStream(f)) { 22 return readFile(is); 23 } 24 } 25 readFile(InputStream is)26 public static String readFile(InputStream is) throws IOException { 27 StringBuilder result = new StringBuilder(); 28 BufferedReader br = new BufferedReader(new InputStreamReader(is)); 29 String line = br.readLine(); 30 while (line != null) { 31 result.append(line + "\n"); 32 line = br.readLine(); 33 } 34 return result.toString(); 35 } 36 writeFile(String string, File f)37 public static void writeFile(String string, File f) throws IOException { 38 f.getParentFile().mkdirs(); 39 FileWriter fw = new FileWriter(f); 40 BufferedWriter bw = new BufferedWriter(fw); 41 bw.write(string); 42 bw.close(); 43 fw.close(); 44 } 45 copyFile(InputStream from, File to)46 public static void copyFile(InputStream from, File to) throws IOException { 47 if (! to.getParentFile().exists()) { 48 to.getParentFile().mkdirs(); 49 } 50 51 try (OutputStream os = new FileOutputStream(to)) { 52 byte[] buffer = new byte[65536]; 53 int count = from.read(buffer); 54 while (count > 0) { 55 os.write(buffer, 0, count); 56 count = from.read(buffer); 57 } 58 } 59 } 60 streamToString(InputStream is)61 public static String streamToString(InputStream is) throws IOException { 62 if (is != null) { 63 Writer writer = new StringWriter(); 64 65 char[] buffer = new char[1024]; 66 try { 67 Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); 68 int n; 69 while ((n = reader.read(buffer)) != -1) { 70 writer.write(buffer, 0, n); 71 } 72 } finally { 73 is.close(); 74 } 75 return writer.toString(); 76 } else { 77 return ""; 78 } 79 } 80 } 81