package com.bit.File;
import java.io.*;
public class TestFileCopy {
//使用字节流实现文件的复制
public static void Copy1(String srcFile,String decFile){
//校验参数合法性
if(srcFile==null || decFile==null){
throw new IllegalArgumentException("参数不能为空");
}
long start = System.currentTimeMillis();
File file1 = new File(srcFile);
File file2 = new File(decFile);
//判断源文件是否为文件是否存在
if(!file1.isFile() || !file1.exists()){
throw new IllegalArgumentException("源文件不是文件或文件不存在");
}
//如果目标目录不存在,则创建
if(!file2.getParentFile().exists()){
file2.getParentFile().mkdir();
}
//实现文件拷贝(先读后写)
try {
InputStream input = new FileInputStream(file1);
OutputStream output = new FileOutputStream(file2);
byte[] bytes = new byte[1024];
int len = -1;
while((len = input.read(bytes))!= -1){
output.write(bytes,0,len);
}
//关闭字节流
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("Copy1消耗的时间:"+(end-start));
}
//使用字符流实现文件拷贝
public static void Copy2(String srcFile,String decFile){
if(srcFile==null || decFile==null){
throw new IllegalArgumentException("参数不能为空");
}
File file1 = new File(srcFile);
File file2 = new File(decFile);
if(!file1.isFile() || !file1.exists()){
throw new IllegalArgumentException("源文件不是文件或源文件不存在");
}
if(!file2.getParentFile().exists()){
file2.getParentFile().mkdir();
}
try {
Reader in = new FileReader(file1);
Writer out = new FileWriter(file2);
char[] chars = new char[10];
int len = -1;
while ((len = in.read(chars))!=-1){
out.write(chars,0,len);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//使用缓冲字节流实现文件拷贝
public static void Copy3(String srcFile,String decFile){
//校验参数合法性
if(srcFile==null || decFile==null){
throw new IllegalArgumentException("参数不能为空");
}
long start = System.currentTimeMillis();
File file1 = new File(srcFile);
File file2 = new File(decFile);
//判断源文件是否为文件是否存在
if(!file1.isFile() || !file1.exists()){
throw new IllegalArgumentException("源文件不是文件或文件不存在");
}
//如果目标目录不存在,则创建
if(!file2.getParentFile().exists()){
file2.getParentFile().mkdir();
}
//实现文件拷贝(先读后写)
try {
BufferedInputStream bs = new BufferedInputStream(new FileInputStream(file1));
BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(file2));
byte[] bytes = new byte[1024];
int len = -1;
while((len = bs.read(bytes))!=-1){
bw.write(bytes,0,len);
}
bs.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//Copy1("F:"+File.separator+"test"+File.separator+"c","F:"+File.separator+"test"+File.separator+"cat2.jpg");
// Copy2("F:"+File.separator+"test"+File.separator+"hello.txt","F:"+File.separator+"test"+File.separator+"bit.txt");
Copy3("F:"+File.separator+"test"+File.separator+"cat.jpg","F:"+File.separator+"test"+File.separator+"cat2.jpg");
}
}
java I/O实现文件的拷贝
最新推荐文章于 2022-08-30 11:31:54 发布