1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| public static void main(String[] args) throws MalformedURLException, IOException { long method1 = System.currentTimeMillis(); for(int i =1 ;i<50000;i++){ InputStream in = new URL( "file:/C:/Users/forgkan/Desktop/readme.txt") .openStream(); inputStream2String1(in); in.close(); } System.out.println("method1 cost:" + (System.currentTimeMillis() - method1) + " ms"); long method2 = System.currentTimeMillis(); for(int i =1 ;i<50000;i++){ InputStream in = new URL( "file:/C:/Users/forgkan/Desktop/readme.txt") .openStream(); inputStream2String2(in); in.close(); } System.out.println("method2 cost:" + (System.currentTimeMillis() - method2) + " ms"); long method3 = System.currentTimeMillis(); for(int i =1 ;i<50000;i++){ InputStream in = new URL( "file:/C:/Users/forgkan/Desktop/readme.txt") .openStream(); inputStream2String3(in); in.close(); } System.out.println("method3 cost:" + (System.currentTimeMillis() - method3) + " ms"); }
public static String inputStream2String1(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }
public static String inputStream2String2(InputStream in) throws IOException { StringBuffer out = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = in.read(b)) != -1;) { out.append(new String(b, 0, n)); } return out.toString(); }
public static String inputStream2String3(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = -1; while ((i = is.read()) != -1) { baos.write(i); } return baos.toString(); }
|