Java 复制文件

package com.gx.testexp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**

  • 复制文件

@author WLX
*
*/
public class TestExp2 {
public static void main(String[] args) throws IOException {
//源文件
String str = “E:/Java学习资料/20190416”;
//目标文件
String str2 = “E:/Java学习资料/20190416Test”;
CopyFile(str, str2);
}
public static void CopyFile(String str, String str2) throws IOException {
//用于读取源文件的子目录或子文件
File file = new File(str);
//根据给定的正则表达式拆分源文件。
String[] s = str.split("/");
//获取源文件的最后一个文件并拼接到目标文件
String str3 = s[s.length - 1];
String str4 = str2 + “/” + str3;
//用于把源文件的子目录或子文件写出到目标文件
File file2 = new File(str4);
//判断源文件是否存在
if(file.exists()) {
//判断源文件是否是目录
if(file.isDirectory()) {
//在目标文件创建该目录
file2.mkdir();
//获取源文件的子目录
String[] f = file.list();
for(String ss : f) {
//递归本方法
CopyFile(str+ “/” + ss, str4);
}
}
else {
//在目标文件创建子文件
file2.createNewFile();
//创建输入流管道
InputStream input = new FileInputStream(file);
//创建输出流管道
OutputStream output = new FileOutputStream(file2);
byte[] by = new byte[1024];
int count = 0;
//在源文件读取该文件的数据
while((count = input.read(by, 0, by.length)) != -1) {
//在目标文件写入该文件的数据
output.write(by,0, count);
}
//关闭输入流
input.close();
// 关闭输出流前强制写出所有输出字节
utput.flush();
//关闭输出流
output.close();
}
}
else {
System.out.println(“文件不存在!”);
}
}
}
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值