2011-06-08 61 views
3

所以我嘗試將文件通過這種方式複製到新的位置:的Java文件複製扭曲文件

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

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

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

其中一期工程的時間細99%。有時候,如果圖像比較小,< = 60x80px,複製的圖像會全部失真。有人知道這裏可能會發生什麼嗎?這裏是複製功能的錯誤,還是我應該在別處尋找?

謝謝。

+1

它很大程度上取決於您的平臺的字符編碼。在大多數編碼中,複製二進制數據將從幾個字節值中摧毀到很多字節組合。如果使用-Dfile.encoding = ISO-8859-1運行程序時,程序突然「有效」,則可以確定在某個地方嘗試使用讀寫器來複制二進制數據。 ISO-8859-1是少數不破壞二進制數據的字符集之一,但取決於您的語言環境文本在顯示時將全部是亂碼。 – mihi 2011-06-08 18:38:24

回答

11

請勿使用Readers/Writers來讀取二進制數據。使用nio軟件包中的InputStreams/OutputStreamsChannels(請參見下文)。從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) { 
} 
+0

對於這個問題,不要使用'Writer'作爲二進制數據。 – Darien 2011-06-08 18:43:40

+0

這是否解決了問題。感謝您的幫助... – gabaum10 2011-06-09 13:24:50

+0

不適合我,我仍然有與我的文件複製後扭曲相同的問題。我的文件幾乎變成了字節大小的兩倍! – 2017-10-12 16:51:52