Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuning the performance of reading a large InputStream in java

Tags:

java

I want to read a large InputStream and return it as a String. This InputStream is a large one. So, normally it takes much time and a lot of memory while it is excuting. The following code is the one that I've developed so far. I need to convert this code as it does the job in a lesser time consuming lesser memory.

Can you give me any idea to do this.

BufferedReader br =
    new BufferedReader(
        new InputStreamReader(
            connection.getInputStream(),
            "UTF-8")
        );

StringBuilder response = new StringBuilder(1000);

char[] buffer = new char[4096];

int n = 0;
while(n >= 0){
    n = br.read(buffer, 0, buffer.length);
    if(n > 0){
        response.append(buffer, 0, n);
    }
}
return response.toString();

Thank you!

like image 586
Namalak Avatar asked Oct 27 '10 07:10

Namalak


People also ask

Which is used for improving the performance while reading the file in Java?

The new JDK 1.1 improves I/O performance with the addition of a collection of Reader and Writer classes. The readLine method in BufferedReader is at least 10 to 20 times faster than the one in DataInputStream when a large file is encountered.

Why is BufferedInputStream faster?

With a BufferedInputStream , the method delegates to an overloaded read() method that reads 8192 amount of bytes and buffers them until they are needed. It still returns only the single byte (but keeps the others in reserve). This way the BufferedInputStream makes less native calls to the OS to read from the file.


2 Answers

When you are doing buffered I/O you can just read one char at a time from the buffered reader. Then build up the string, and do a toString() at the end.

like image 57
Thorbjørn Ravn Andersen Avatar answered Nov 09 '22 19:11

Thorbjørn Ravn Andersen


You may find that for large files on some operating systems, mmaping the file via FileChannel.map will give you better performance - map the file and then create a string out of the mapped ByteBuffer. You'll have to benchmark though, as it may be that 'traditional' IO is faster in some cases.

like image 24
Steven Schlansker Avatar answered Nov 09 '22 18:11

Steven Schlansker