Java文件复制问题?
运行结果:文件复制成功,但是在判断是否是文件夹时,程序已经进入,文件夹却创建失败,不知道是怎么回事,望大佬解答。//将给定路径1下所有文件和文件夹复制到给定路径2中pub...
运行结果:文件复制成功,但是在判断是否是文件夹时,程序已经进入,文件夹却创建失败,不知道是怎么回事,望大佬解答。
// 将给定路径1下所有文件和文件夹复制到给定路径2中
public static void main(String[] args) throws IOException {
String oldPath = "E:\\test";
String newPath = "E:\\test01";
File f = new File(oldPath);
File[] listFiles = f.listFiles();
for (File file : listFiles) {
copy(file, newPath + "\\" + file.getName());
}
}
@SuppressWarnings("resource")
private static void copy(File file, String newPath) throws IOException {
if (file.isFile()) {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));// 读
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newPath));// 写
// 复制流程 读--写
byte[] by = new byte[1024];
int len = 0;
while ((len = bis.read(by)) != -1) {
bos.write(by, 0, len);
}
bis.close();
bos.close();
} else if (file.isDirectory()) {
//在新路径中创建文件夹
File file3 = new File(newPath + "\\" + file.getName());
boolean mkdir = file3.mkdir();
File[] listFiles = file.listFiles();
for (File file2 : listFiles) {
copy(file2, newPath);
}
}
} 展开
// 将给定路径1下所有文件和文件夹复制到给定路径2中
public static void main(String[] args) throws IOException {
String oldPath = "E:\\test";
String newPath = "E:\\test01";
File f = new File(oldPath);
File[] listFiles = f.listFiles();
for (File file : listFiles) {
copy(file, newPath + "\\" + file.getName());
}
}
@SuppressWarnings("resource")
private static void copy(File file, String newPath) throws IOException {
if (file.isFile()) {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));// 读
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newPath));// 写
// 复制流程 读--写
byte[] by = new byte[1024];
int len = 0;
while ((len = bis.read(by)) != -1) {
bos.write(by, 0, len);
}
bis.close();
bos.close();
} else if (file.isDirectory()) {
//在新路径中创建文件夹
File file3 = new File(newPath + "\\" + file.getName());
boolean mkdir = file3.mkdir();
File[] listFiles = file.listFiles();
for (File file2 : listFiles) {
copy(file2, newPath);
}
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询