| 1 19 20 21 35 package edu.umd.cs.findbugs.io; 36 37 import java.io.BufferedReader ; 38 import java.io.IOException ; 39 import java.io.InputStream ; 40 import java.io.InputStreamReader ; 41 import java.io.OutputStream ; 42 import java.io.Reader ; 43 import java.io.StringWriter ; 44 import java.io.Writer ; 45 46 public class IO { 47 static ThreadLocal <byte[]> myByteBuf = new ThreadLocal <byte[]>() { 48 @Override  49 protected byte[] initialValue() { 50 return new byte[4096]; 51 } 52 }; 53 static ThreadLocal <char[]> myCharBuf = new ThreadLocal <char[]>() { 54 @Override  55 protected char[] initialValue() { 56 return new char[4096]; 57 } 58 }; 59 60 public static String readAll(InputStream in) throws IOException { 61 return readAll(new InputStreamReader (in)); 62 } 63 64 public static String readAll(Reader reader) throws IOException { 65 BufferedReader r = new BufferedReader (reader); 66 StringWriter w = new StringWriter (); 67 copy(r, w); 68 return w.toString(); 69 } 70 71 public static long copy(InputStream in, OutputStream out) 72 throws IOException { 73 return copy(in, out, Long.MAX_VALUE); 74 } 75 76 public static long copy(Reader in, Writer out) 77 throws IOException { 78 return copy(in, out, Long.MAX_VALUE); 79 } 80 81 82 public static long copy(InputStream in, OutputStream out, 83 long maxBytes) 84 85 throws IOException { 86 long total = 0; 87 88 int sz; 89 90 byte buf [] = myByteBuf.get(); 91 92 while (maxBytes > 0 && 93 (sz = in.read(buf, 0, 94 (int) Math.min(maxBytes, (long) buf.length))) 95 > 0) { 96 total += sz; 97 maxBytes -= sz; 98 out.write(buf, 0, sz); 99 } 100 return total; 101 } 102 103 public static long copy(Reader in, Writer out, 104 long maxChars) 105 106 throws IOException { 107 long total = 0; 108 109 int sz; 110 111 char buf [] = myCharBuf.get(); 112 113 while (maxChars > 0 && 114 (sz = in.read(buf, 0, 115 (int) Math.min(maxChars, (long) buf.length))) 116 > 0) { 117 total += sz; 118 maxChars -= sz; 119 out.write(buf, 0, sz); 120 } 121 return total; 122 } 123 124 130 public static void close(InputStream inputStream) { 131 if (inputStream == null) { 132 return; 133 } 134 135 try { 136 inputStream.close(); 137 } catch (IOException e) { 138 } 140 } 141 142 148 public static void close(OutputStream outputStream) { 149 if (outputStream == null) { 150 return; 151 } 152 153 try { 154 outputStream.close(); 155 } catch (IOException e) { 156 } 158 } 159 } 160 | Popular Tags |