javaiofileinputstreambufferedinputstreambufferedoutputstream

BufferOutputStream write zero byte when merge the file


I am trying merge n pieces of file become single file. But I got strange behavior on my function. The function are called for x times in n seconds. Let say I have 100 files which I will merge, every second I call 5 files and merger it. and in the next second the amount is double to be 10, but from 1-5 is the same file as before the rest is new file. It work normal but in some point, its give zero byte or sometime give the right size.

Could you help me spot the mistake in my function below?

public void mergeFile(list<String> fileList, int x) {
    int count = 0;
    BufferedOutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream("Test.doc"));
        for (String file : fileList) {
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            byte[] buff = new byte[1024];
            in.read(buff);
            out.write(buff);
            in.close();
            count++;
            if (count == x) {
                break;
            }
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

*sorry for my English


Solution

  • in.read(buff);

    Check the Javadoc. That method isn't guaranteed to fill the buffer. It returns a value which tells you how many bytes it read. You're supposed to use that, and in this situation you are supposed to use it when deciding how many bytes, if any, to write.