封装了集中常用的文件读的方法
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();
}
}
}
相关文章
- linux中,查看某个进程打开的文件数?
- zip 文件下载函数封装
- ant使用ssh和linux交互 如:上传文件
- VS Code插件开发学习笔记2-开发一个Vivado Report文件高亮的插件
- 【用ddt思想重构项目】Selenium使用json模块读取json文件、使用pytest参数化实现DDT
- shell:读取文件的每一行内容并输出
- Apache限制访问某目录或某文件,限制允许指定IP
- vue项目构建实战基础知识:SPA理解/RESTful接口介绍/static目录配置/axios封装/打包时map文件去除
- Hive合并小文件的配置项
- Linux中sudo命令及sudoers文件
- 2.31 OrCAD中怎么批量更新封装库文件?
- 接口 web api Swagger 文件上传
- 调试接口小技巧-通过接口调试工具去下载上传文件
- 文件上传accept 属性 文件上传只能上传固定格式