此处我使用的是使用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);