您的位置:首页 > 编程语言 > Java开发

java 文件的复制方法

2017-02-19 14:34 316 查看
方法一、采用IO流的方法

/**
* 文件复制方法1
* 方法名:文件复制
* 开发者:wangql
* 开发时间:2017-2-18
*/
public static void fileCopy(String source, String target) throws IOException {
try (InputStream in = new FileInputStream(source)) {
try (OutputStream out = new FileOutputStream(target)) {
byte[] buffer = new byte[4096];//4096 = 4K,开辟4K的缓冲区
int bytesToRead;
while((bytesToRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
}
}
}
方法二、采用NIO流的方法

/**
* 文件复制方法2
* 方法名:文件复制
* 开发者:wangql
* 开发时间:2017-2-18
*/
public static void fileCopyNIO(String source, String target) throws IOException {
try (FileInputStream in = new FileInputStream(source)) {
try (FileOutputStream out = new FileOutputStream(target)) {
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);//从堆空间中分配一个容量大小为capacity的byte数组作为缓冲区的byte数据存储器
while(inChannel.read(buffer) != -1) {
buffer.flip();
outChannel.write(buffer);
buffer.clear();
}
}
}
}
调用方法实现
public static void main(String[] args) {
int sum = countWordInFile("C://Users/diyvc/Desktop/test.txt", "a");
System.out.println(sum);
try {
fileCopy("C://Users/diyvc/Desktop/test.txt","C://Users/diyvc/Desktop/copy.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: