可能是最完美的Android複製拷貝檔案的例項(Java NIO速度快)
阿新 • • 發佈:2019-02-03
此處我使用的是使用Java NIO中的管道到管道傳輸,包括了transferFrom方法。
經過測試比檔案流複製的速度更快!
private final static String FileName = "a23.wav";
/**
* 根據檔案路徑拷貝檔案
* @param src 原始檔
* @param destPath目標檔案路徑
* @return boolean 成功true、失敗false
*/
public boolean copyFile(File src, String destPath) {
boolean result = false ;
if ((src == null) || (destPath== null)) {
return result;
}
File dest= new File(destPath + FileName);
if (dest!= null && dest.exists()) {
dest.delete(); // delete file
}
try {
dest.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileChannel srcChannel = null ;
FileChannel dstChannel = null;
try {
srcChannel = new FileInputStream(src).getChannel();
dstChannel = new FileOutputStream(dest).getChannel();
srcChannel.transferTo(0, srcChannel.size(), dstChannel);
result = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return result;
} catch (IOException e) {
e.printStackTrace();
return result;
}
try {
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
使用copyFile函式
private static final String AUDIO_FILE_PATH =
Environment.getExternalStorageDirectory().getPath();
File file = new File(); // 此處為虛擬碼,實際為一個真實存在的檔案,即你想複製的檔案。
copyFile(file, AUDIO_FILE_PATH);