Java I / O性能Streams vs Reader / Writer

时间:2014-04-07 07:40:03

标签: java buffer streamwriter inputstreamreader

我尝试过两段Java 1.7代码:

摘录1:

try {
    BufferedReader in = new BufferedReader(
                    new InputStreamReader(myInputStream)); //from the Internet  
     String s;
     out = new PrintWriter(new BufferedWriter(new FileWriter("file")));
     while ((s = in.readLine()) != null){
         out.write (s);
      }
      in.close();
      out.close();
} catch (Exception e) {
    e.printStackTrace();
}

摘录2:

try {
    BufferedInputStream in = new BufferedInputStream(
                         myInputStream);   //from the Internet 
        out = new BufferedOutputStream(new FileOutputStream("file")); 
        byte[] data = new byte[1024]; // 1 Kb randomly chosen as my buffer
        int len=0;
        while ((len=in.read(data)) != -1) {
            out.write(data,0,len);
        }
        in.close();
        out.close();
 } catch (Exception e) {
     e.printStackTrace();
 }

Snippet 1似乎比代码片段2快2到6倍。但是,我需要使用Snippet 2,因为我正在读取字节流。有没有办法改善代码片段2的性能,以便更紧密地匹配代码片段1?我做错了吗?

0 个答案:

没有答案