Java Copy Files

So, I am trying to copy a file to a new location as follows:

FileReader in = new FileReader(strTempPath);
FileWriter out = new FileWriter(destTempPath);

int c;
while ((c = in.read()) != -1){
    out.write(c);
}

in.close();
out.close();

Which works fine in 99% of cases. Sometimes, if the image is quite small, <= 60x80px, the copied image leaves all the distortions. Does anyone know what can happen here? Is this a copy function error here or should I look elsewhere?

Thank.

+3
source share
2 answers

Do not use Readers/ Writersto read binary data. Use InputStreams/ OutputStreamsor Channelsfrom the nio package (see below).

Example from exampledepot.com :

try {
    // Create channel on the source
    FileChannel srcChannel = new FileInputStream("srcFilename").getChannel();

    // Create channel on the destination
    FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel();

    // Copy file contents from source to destination
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

    // Close the channels
    srcChannel.close();
    dstChannel.close();
} catch (IOException e) {
}
+11
source