博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
封装了集中常用的文件读的方法
阅读量:7236 次
发布时间:2019-06-29

本文共 2028 字,大约阅读时间需要 6 分钟。

package com.opslab.util.algorithmImpl;

import java.io.*;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**

* 封装了集中常用的文件读的方法
*/
public class FileReadImpl {

/**

* 利用FileChannel直接实现文件的对拷,对于大文件速度特别明显
*
* @param source
* @param target
*/
public static void copyFileWithChannel(File source, File target) {
try (
FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = new FileOutputStream(target);
FileChannel in = inStream.getChannel();
FileChannel out = outStream.getChannel();
) {
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
}
}

/**

* 使用FileChannel+Buffer实现文件的读取拷贝是一种极佳的方案
*
* @param source
* @param target
*/
public static void copyFileWithBuffer(File source, File target) {
try (
FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = new FileOutputStream(target);
FileChannel in = inStream.getChannel();
FileChannel out = outStream.getChannel()
) {
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**

* 利用Buffer实现文件的读取拷贝
*
* @param source
* @param target
*/
public static void customBufferBufferedStreamCopy(File source, File target) {
try (
InputStream fis = new BufferedInputStream(new FileInputStream(source));
OutputStream fos = new BufferedOutputStream(new FileOutputStream(target))
) {
byte[] buf = new byte[4096];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**

* 利用Buffer实现文件的读取拷贝
*
* @param source
* @param target
*/
public static void customBufferStreamCopy(File source, File target) {
try (
InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target);
) {
byte[] buf = new byte[4096];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

转载于:https://www.cnblogs.com/chinaifae/p/10254640.html

你可能感兴趣的文章
http请求
查看>>
国学与科学:如何培养中国人的科学创新思考技术
查看>>
MergeSort (归并排序)
查看>>
1-CLR线程池的作用与原理浅析
查看>>
近似pi
查看>>
[Unity3D]程序退出进程及资源问题
查看>>
mysql导出表结构不导出数据
查看>>
zabbix安装出现的问题
查看>>
华为eNSP GRE
查看>>
赚钱的这些年(上)苦逼
查看>>
我的友情链接
查看>>
HttpServletResponse常用方法介绍
查看>>
国内ip地址 透明代理
查看>>
Lua1.1 Lua 的参考手册 (一)
查看>>
Lua5.0 非正式总结
查看>>
vsftpd基础详解及安装配置案例
查看>>
nginx修改上传文件大小限制
查看>>
for循环语句示例应用
查看>>
OpenLDAP集成TLS/SSL
查看>>
为什么技多不压身, 却让你更迷茫了?
查看>>