Java: File copy getting 0 bytes

4

I backup the database normally and saved to a folder using getRuntime (). exec (). I use a very simple method to copy this file using FileChannel.

But it turns out the copy is 0 bytes long. It copies the file before it is complete.

Any tips on how to avoid this?

Putting Loops I do not think it would be trivial, I do not know.

Here is the code used for copying:

public static void copyFile(File source, File destination) throws IOException {
        if (destination.exists())
            destination.delete();
        FileChannel sourceChannel = null;
        FileChannel destinationChannel = null;
        try {
            sourceChannel = new FileInputStream(source).getChannel();
            destinationChannel = new FileOutputStream(destination).getChannel();
            sourceChannel.transferTo(0, sourceChannel.size(),
                    destinationChannel);
        } finally {
            if (sourceChannel != null && sourceChannel.isOpen())
                sourceChannel.close();
            if (destinationChannel != null && destinationChannel.isOpen())
                destinationChannel.close();
       }
   }
    
asked by anonymous 25.07.2017 / 16:03

3 answers

0

Thank you all!

I looked at the whole code more closely, and the problem itself was not in the copying method.

To resolve, in the Runtime that generated the file was modified. In short, the modification that he resolved was:

Before:

Runtime.getRuntime().exec(comando);

Stayed:

Process process = Runtime.getRuntime().exec(comando);
if(process.waitFor() <= 0) {
 copyFile(origem, destino);
}

The copy is perfectly done.

Thank you again for your attention!

    
26.07.2017 / 20:28
0

Try using the byteBuffer class as follows

FileChannel sourceChannel = null;
FileChannel destinationChannel = null;
try {
    sourceChannel = new FileInputStream(source).getChannel();
    destinationChannel = new FileOutputStream(destination).getChannel();
    ByteBuffer buff = ByteBuffer.allocate(32 * 1024);

    while (sourceChannel.read(buff) > 0) {
      buff.flip();
      destinationChannel.write(buff);
      buff.clear();
    }
} finally {
    if (sourceChannel != null && sourceChannel.isOpen())
        sourceChannel.close();
    if (destinationChannel != null && destinationChannel.isOpen())
        destinationChannel.close();
}
    
25.07.2017 / 18:14
0

Easier and more effective if you simply copy the file without reading / writing the content:

import static java.nio.file.StandardCopyOption.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

...

public static void copyFile(File source, File destination) throws IOException {
    Files.copy(source.toPath(), destination.toPath(), REPLACE_EXISTING, COPY_ATTRIBUTES);
}

It's hardly worth writing a method ... you should also consider working directly with Path instead of File .

    
26.07.2017 / 15:45