Tag Archives: buffered streams

java.io.BufferedInputStream and java.util.zip.GZIPInputStream

by Mikhail Vorontsov

BufferedInputStream and GZIPInputStream are two classes often used while reading some data from a file (the latter is widely used at least in Linux). Buffering input data is generally a good idea which was described in many Java performance articles. There are still a couple of issues worth knowing about these streams.

When not to buffer

Buffering is done in order to reduce number of separate read operations from an input device. Many developers often forget about it and always wrap InputStream inside BufferedInputStream, like

1
final InputStream is = new BufferedInputStream( new FileInputStream( file ) );
final InputStream is = new BufferedInputStream( new FileInputStream( file ) );

The short rule on whether to use buffering or not is the following: you don’t need it if your data blocks are long enough (100K+) and you can process blocks of any length (you don’t need any guarantees that at least N bytes is available in the buffer before starting processing). In all other cases you need to buffer input data.

The simplest example when you don’t need buffering is a manual file copy process.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void copyFile( final File from, final File to ) throws IOException {
    final InputStream is = new FileInputStream( from );
    try
    {
        final OutputStream os = new FileOutputStream( to );
        try
        {
            final byte[] buf = new byte[ 8192 ];
            int read = 0;
            while ( ( read = is.read( buf ) ) != -1 )
            {
                os.write( buf, 0, read );
            }
        }
        finally {
            os.close();
        }
    }
    finally {
        is.close();
    }
}
public static void copyFile( final File from, final File to ) throws IOException {
    final InputStream is = new FileInputStream( from );
    try
    {
        final OutputStream os = new FileOutputStream( to );
        try
        {
            final byte[] buf = new byte[ 8192 ];
            int read = 0;
            while ( ( read = is.read( buf ) ) != -1 )
            {
                os.write( buf, 0, read );
            }
        }
        finally {
            os.close();
        }
    }
    finally {
        is.close();
    }
}

Continue reading