FileChannel优势【待继续探究】:
1.多线程并发读写,并发性;
2.IO读写性能提高(OS负责),也可引做共享内存,减少IO操作,提升并发性;
3.应用crash,保证这部分内容还能写的进去文件。在我们调用channel.write(bytebuffer)之后,具体何时写入磁盘、bytebuffer中内容暂存于哪里(os cache)等相关一系列问题,就交由OS本身负责了。
FileChannel的优点包括:
- 在文件特定位置进行读写操作
- 将文件一部分直接加载到内存,这样效率更高
- 以更快的速度将文件数据从一个通道传输到另一个通道
- 锁定文件的某一部分来限制其他线程访问
- 为了避免数据丢失,强制立即将更新写入文件并存储
/**
* 根据文件路径拷贝文件
* @param src 源文件
* @param destPath 目标文件路径
* @return boolean 成功true、失败false
*/
public static boolean copyFile(File src, String destPath, String destFileName) {
if ((src == null) || (destPath== null)) {
return false;
}
File dest = new File(destPath, destFileName);
if (dest.exists()) {
boolean isSuccess = dest.delete();
if (!isSuccess) {
return false;
}
}
try {
boolean isSuccess = dest.createNewFile();
if (!isSuccess) {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
boolean result = false;
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 (IOException e) {
e.printStackTrace();
} finally {
try {
if (srcChannel != null) {
srcChannel.close();
}
if (dstChannel != null) {
dstChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}