Java拷贝文件扭曲文件

gab*_*m10 3 java file-io file-copying

所以我试图通过这种方式将文件复制到新位置:

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

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

in.close();
out.close();
Run Code Online (Sandbox Code Playgroud)

99%的情况下工作正常.有时,如果图像相当小,<= 60x80像素,则复制的图像会全部失真.有谁知道这里会发生什么?这是复制功能的错吗,还是我应该在其他地方寻找?

谢谢.

aio*_*obe 11

不要使用Readers/ Writers来读取二进制数据.使用InputStreams/ OutputStreamsChannels来自nio包(见下文).

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) {
}
Run Code Online (Sandbox Code Playgroud)