1. FileChannel 使用场景:
一个读,写,映射,操作文件的通道。
2 使用的优点
1.在文件的绝对位置的字节读写操作在某种程度上不会影响通道的当前位置。
2.文件的区域可能会被直接映射到内存中,对于大文件来说,这比通常的读写方法更有效。
3.为了保证数据在系统崩溃之后不丢失数据,文件的修改模式会被强制到底层存储设备。
4.字节能从一个文件被转换为一些其他的通道,反之亦然,这种操作在某种程度上会被许多操作系统或者文件系统优化成一个非常快速的直接传输。
5.文件的区域也许会被锁住来防止其它程序的访问。
文件复制小DEMO
/**
* 用filechannel进行文件复制
*
* @param fromFile 源文件
* @param toFile 目标文件
*/
public void fileCopyWithFileChannel(File fromFile, File toFile) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
FileChannel fileChannelInput = null;
FileChannel fileChannelOutput = null;
try {
fileInputStream = new FileInputStream(fromFile);
fileOutputStream = new FileOutputStream(toFile);
//得到fileInputStream的文件通道
fileChannelInput = fileInputStream.getChannel();
//得到fileOutputStream的文件通道
fileChannelOutput = fileOutputStream.getChannel();
//将fileChannelInput通道的数据,写入到fileChannelOutput通道
fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null)
fileInputStream.close();
if (fileChannelInput != null)
fileChannelInput.close();
if (fileOutputStream != null)
fileOutputStream.close();
if (fileChannelOutput != null)
fileChannelOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
项目中的 使用场景
@Override
public String upload(String type, InputStream inputStream) {
FileOutputStream out = null;
FileChannel channel = null;
ByteBuffer buffer = null;
try {
String name = IdGenerateUtil.generateId(type);
String fileName = dir + name;
out = new FileOutputStream(fileName);
channel = out.getChannel();
buffer = ByteBuffer.wrap(readStream(inputStream));
out.flush();
channel.write(buffer);
return name;
} catch (Exception e) {
LOGGER.error(LogBuilderUtil.getBuilder("upload", "上传文件", "Exception").build(), e);
} finally {
try {
channel.close();
out.close();
} catch (IOException e) {
LOGGER.error(LogBuilderUtil.getBuilder("upload", "上传文件", "finally-Exception").build(), e);
}
}
return null;
}