javajava-iobufferedinputstreambufferedoutputstream

How do I use Buffered streams to append to a file in Java?


I have the following code, but I'm not sure that i'm doing everything correctly in terms of efficiency/flushing/closing streams. Some advice would greatly help, thank you

    OutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream(file, true));
        byte[] buf = new byte[32 * 1024]; // should this be 32KB?
        while ((in.read(buf)) > 0) {
            out.write(buf);
        }
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();
            if (in != null)
                in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Solution

  • The most important issue you have is that you are ignoring how many bytes you read.

    for(int len; (len = in.read(buf)) > 0;) 
            out.write(buf, 0, len);
    

    If you don't use the length you are assuming you will always read exactly 32 KB, this is a big assumption.


    Buffers are useful when you have lots of small writes.

    The default buffered size for BufferedOutputStream is 8 KB and if your writes are much smaller than this i.e. < 512 bytes they can really help.

    However, if you are writing say 32 KB they are probably doing nothing, or not helping. I would take them out.

    BTW, without a buffer, you don't need to call flush();

    BTW2

    KB = 1024 bytes
    kB = 1000 bytes
    Kb = 1024 bits
    kb = 1000 bits.