Question

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

Was it helpful?

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.

OTHER TIPS

You do not read the full file, you read from each file only up to 1024 bytes. You need to loop the read as long as it returns data (or use something like Files.copy().

BTW: you dont need a BufferedOutputStream if you copy with large buffers.

public void mergeFile(list<String> fileList, int x) throws IOException {
    try (OutputStream out = new FileOutputStream("Test.doc");) {
        int count=0;
        for (String file : fileList) {
            Files.copy(new File(file).toPath(), out);
            count++;
            if (count == x) {
                break;
            }
        }
    }
}

You also do not need to flush() if you close. I am using "try-with-resource" here, so I dont need to close it explicitely. It is best to propagate the exceptions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top