难度在与怎么同步复制文件路径 可以同样利用递归文件夹的方式,把将要递归的路径在进行递归,然后每次进行更新。
附源码
package cn.edu.shengda;
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;
/**
*
* 文件以及文件夹的拷贝
* @author 书生
*
*/
public class Test5_copy {
public static void main(String[] args) {
// copy_File("abc.txt", "def.txt");
File file = new File("G:\\Java_Study\\IO流_01");// 读入文件夹
mkdirs_Wenjian(file, "G:\\java_Study\\IO流_copy");// 后一个为要写入的文件路径
}
public static void mkdirs_Wenjian(File file, String writesrc) { // 文件夹的复制
if (file == null || !file.exists()) { // 如果文件不存在 或文件 为空 跳出
return;
}
if (file.isFile()) { // 如果是文件
String str = writesrc + '\\' + file.getName(); // 修改将要写入的文件夹路径
File readFile = new File(str); // 将要写入的路径
InputStream os = null; // 输入源
OutputStream is = null; // 输出源
try {
os = new FileInputStream(file);
is = new FileOutputStream(readFile);
byte [] temp = new byte[1024]; // 存放字节
int len = -1;
while ((len = os.read(temp)) != -1) { // 读取数据
is.write(temp, 0, len); // 将读入的数据进行写入
is.flush(); // 刷新
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally { // 关闭输入输出流
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (file.isDirectory()) { // 如果是文件夹
String str = writesrc + '\\' + file.getName(); // 将要写入的路径
File kk = new File(str);
kk.mkdirs(); // 创建将要写入路径没有得文件夹
File [] flag = file.listFiles(); // 将文件夹里的文件放入一个列表
for (File tempFile : flag) { // 遍历
mkdirs_Wenjian(tempFile, str); // 递归 传入要读入的路径,同步更新要写入的路径
}
}
}
public static void copy_File(String readsrc, String writesrc) { // 复制文件 同上
File readFile = new File(readsrc);
File writeFile = new File(writesrc);
InputStream iStream = null;
OutputStream oStream = null;
try {
iStream = new FileInputStream(readFile);
oStream = new FileOutputStream(writeFile);
int len = -1;
byte [] datas = new byte[1024];
while ((len = iStream.read(datas)) != -1) {
oStream.write(datas, 0, len);
// String str = new String(datas, 0, len);
// System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (oStream != null) {
oStream.close();
}
}catch (IOException e) {
e.printStackTrace();
}
try {
if (iStream != null) {
iStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}