//创建一个copy 文件的方法
public static void copyfile(File src,File docfile)throws Exception{
//创建一个文件输入流
FileInputStream input = new FileInputStream(src);
//创建一个文件输出流
FileOutputStream out =new FileOutputStream(docfile);
//方法一str
//定义一个变量接受读取到的字节
/* int b = -1;
while ((b=input.read())!=-1){
//System.err.println((char) b); // 把b接受的字符转成char 其实打印的就是计算机编码
//把读到的字节写入到目标文件
out.write(b);
}*/
//方法一end 方法二str 如果文件较大也可以设置缓冲区 如下;
/*
*下面是设置了缓存区 相比上边方法效率要高很多
* 相比上边的方法有点像喝水 每次一滴一滴喝 不太过瘾 加缓存区好比是那杯子接满了 一下喝完 杯子就是我们下边声明的数组;
*
**/
//定义一个用来缓冲的数组 就是每次读到的字节先放到缓存区然后一并输出提高效率;
byte[] b = new byte[1024];
//用来接收每次读到的字节数量;
int len = -1;
//read(byte[]) 读取一定数量的字节也就是参数设置的大小 放到缓存区 返回每次读取的字节数量 read() 返回每次读取到的字节;
while ((len=input.read(b))!=-1){
//将缓存区的字节输出到目标文件 因为文件末尾读到的字节数不确定所以 每次输出缓存区的 0 到 实际读到的字节长度;
out.write(b,0,len);
}
//因为输入出流用到系统级资源 所以要关流释放资源;
input.close();
out.close();
}
public static void main(String[] sage){
//要复制的 源文件
File file =new File("E:\\加班记录.txt");
//目标文件路径
String filePath="E:\\copy\\copy2\\copy3";
File docParent= new File(filePath);
//判断当前文件或文件夹是否存在;
if(!docParent.exists()){
//如果路径目录不存在创建文件目录
docParent.mkdirs();
//值创建子目录 如:创建copy3目录 copy2 必须存在否则不创建 mkdirs()是创建所有目录;
// docParent.mkdir();
}
//创建一个目标文件;
File docFile =new File(filePath+File.separator+"copy加班记录.txt");
try {
//执行copy方法;
copyfile(file,docFile);
} catch (Exception e) {
e.printStackTrace();
}
}