1

I have tried two snippets of Java 1.7 code:

Snippet 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();
}

Snippet 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 seems to perform approximately 2 to 6 times faster than snippet 2. However, I need to use Snippet 2 because I am reading a byte stream. Is there any way to improve the performance of snippet 2 so that it more closely matches snippet 1? Am I doing something wrong?

Java Addict
  • 175
  • 8

0 Answers0