import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* ClassName: CopyFileDemo
* @Description: 指定一个盘符下的文件,把该文件复制到指定的目录下
* @author cai
* @date 2018年10月16日
*
* 文件的复制:
* 从一个输入流读数据,然后通过输出流写入目标位置
*/
public class CopyFileDemo {
public static void main(String[] args) {
System.out.println("start copy...");
copy("C:\\Users\\Desktop\\需要被删的\\新建文本文档 (2).txt", "C:\\Users\\Desktop\\需要被删的\\新建文本文档 (3).txt");
System.out.println("copy success!");
}
private static void copy(String src, String target) { //此处两个形参分别表示字符串形式的两个路径
File srcFile = null;
File targetFile = null;
try {
InputStream in= new FileInputStream(filesrc); //创建字节输入流并实例化字节输出流对象
OutputStream out = new FileOutputStream(filetarg); //创建字节输出流并实例化字节输入流对象
byte[] bytes = new byte[1024]; //创建数组用于接收字节数
int len = -1; //read()返回值为-1时表面已经读完
while((len =in.read(bytes)) != -1) { //调用read方法开始读文件
out.write(bytes, 0, len); //调用write方法写入文件
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}