Java: Copy file with 0 bytes

Asked

Viewed 124 times

4

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

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

Any tips on how to avoid this?

Putting loopings I don’t think would be trivial, I don’t know.

Below is 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();
       }
   }
  • How are you making these copies? Add the code.

  • Hello Articuno, follow the code in the issue of the question. Thank you.

  • The code worked properly for me. What kind of file is being copied?

2 answers

0


Thank you all!

I analyzed all the code more carefully, and the problem itself was not in the method that made the copy.

To solve, in the Runtime generating the file was modified. In short, the modification he resolved was:

Before:

Runtime.getRuntime().exec(comando);

Became:

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

With this the copy is made perfectly.

Thank you again for your attention!

0

Try using the byteBuffer class as below

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();
}
  • I edited the code with the correct variables

Browser other questions tagged

You are not signed in. Login or sign up in order to post.