Java实现文件复制的方法集
1.Java IO
public void JavaCopyFile(){
//1.创建一个字节输入流对象,构造方法中绑定要读取的数据源
File source = new File("D:/copy.txt");
//2.创建一个字节输出流对象,构造方法中绑定要写入的目的地
File target = new File("D:/Download/javaIO.txt");
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(target);
//3.使用数组缓冲读取多个字节,写入多个字节
byte[] b = new byte[1024];
int n = 0;
while ((n = is.read(b)) != -1) {
//4.使用字节输出流中的方法write,把读取到的字节写入到目的地的文件中
os.write(b, 0, n);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//5.关闭流
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.FileChannel
public void JavaCopyFile(){
File source = new File("D:/copy.txt");
File target = new File("D:/Download/FileChannel.txt");
FileChannel input = null;
FileChannel output = null;
try {
input = new FileInputStream(source).getChannel();
output = new FileOutputStream(target).getChannel();
output.transferFrom(input, 0, input.size());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.Commons IO组件
FileUtils.copyFile(Source , Target);
public void JavaCopyFile() throws IOException {
File source = new File("D:/copy.txt");
File target = new File("D:/Download/CommonsIO.txt");
FileUtils.copyFile(source, target);
}
4.Java7的Files类
public void JavaCopyFile() throws IOException {
File source = new File("D:/copy.txt");
File target = new File("D:/Download/Files.txt");
Files.copy(source.toPath(), target.toPath());
}