Is it possible to copy files without using stream buffer?

4

In my application, I have a class that periodically backs up a pretty small (less than 1MB) file, but I'm doing some testing and after reading this answer , it seems to me that it has been suggested that you can make copies without having to use buffer . With the code below, I'm using buffer of 4kb, and the result is quite satisfactory.

Here is the code I'm using:

private static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst); 
    byte[] buf = new byte[4096];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

Is it possible to copy without using buffer ? Does removing the buffer really optimize the copy of files?

    
asked by anonymous 05.12.2016 / 11:58

1 answer

4

In my opinion, after some evaluation, if I understood the question, it is not possible .

Copying without using buffer is possible using DMA , so it does not even go through memory. This operation must be atomic, ie it can not be a read and then a writing, it has to be something simultaneous (same), it has to be something done by the hardware under the command of the operating system. I do not know if Java gives access to the DMA, and if that complies, it would have to do something in C by calling the specific API and exposing it to Java, probably with JNI .

But as streams , at least those available in the Java API must be either read or write, a buffer is required. With this API it is not possible, you would need to use an API that does not require an intermediate process.

I believe it's only possible to do FileChannel . Even this I can not claim to use the DMA. The documentation does not make anything clear about this and may be implementation detail.

Other options give clues that use buffer .

Removing the buffer certainly gives a great gain in performance since it does not have to go through memory, just do not expect miracles, after all the memory is fast and the secondary storage is still slow. / p>     

05.12.2016 / 13:01