File类实现文件夹和文件复制

时间:2023-03-08 22:04:50
File类实现文件夹和文件复制
package com.jcy.copy;

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; public class FolderAllCopy { /**
* 复制文件夹
*
* @param oldPath
* 被复制的文件夹
* @param newPath
* 要复制到的文件夹
*/
public static void copyFolder(String oldPath, String newPath) { File newFile = new File(newPath); File oldFile = new File(oldPath); if (!oldFile.isDirectory()) {// 判断是不是文件夹
copyFile(oldPath, newPath);
return;
}
// 获得复制文件夹路径的字符串长度
int len = oldPath.length();
// 得到该文件夹的所有文件和文件夹
File[] files = oldFile.listFiles();
copy(files, newPath, len);
} private static void copy(File[] files, String newPath, int len) {
if (files == null) {
return;
}
for (File file : files) {
if (file.isDirectory()) {// 是否为文件夹
copy(file.listFiles(), newPath, len);
}
// System.out.println(file.getName());
// eg: newPath : f:\\ss
// oldPath : d:\\ww --> len
// file : d:\\ww\\ee\\d.txt
// ==> \\ee\\d.txt
// ==> newPath + path f:\\ss\\ee\\d.txt
String path = file.getAbsolutePath().substring(len,
file.getAbsolutePath().length()); if (file.isFile()) {// 是否为文件
copyFile(file.getPath(), newPath + path);
} } } /**
* 单个文件复制
*
* @param oldPath
* 复制的文件路径
* @param newPath
* 复制到的目标地
* @return
*/
public static boolean copyFile(String oldPath, String newPath) { //System.out.println(oldPath);
//System.out.println(newPath);
File oldFile = new File(oldPath); if (!oldFile.exists()) {
System.out.println("源文件不存在。" + oldFile.exists());
return false;
}
if (!oldFile.canRead()) {
System.out.println("源文件不可以读");
return false;
} // 得到文件和文件夹的名
String fileName = oldFile.getName();
String[] strs = fileName.split("\\.");
// 对目标路径进行处理
if (!newPath.endsWith("." + strs[strs.length - 1])) {// 传入的路径不是 .XXX
if (newPath.endsWith("\\")) {// 传入的路径是文件夹 \\
newPath += fileName;
} else {
newPath += File.separator + fileName;
}
}
if (!oldFile.isFile()) {
return false;
}
File newFile = new File(newPath); // 验证新路径的文件夹是否存在
if (!newFile.getParentFile().exists()) {
// 文件夹不存在时,创建文件夹
newFile.getParentFile().mkdirs();
} InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(oldFile);
out = new FileOutputStream(newFile);
byte[] b = new byte[1024];
int temp = 0;
while ((temp = in.read(b)) != -1) {
out.write(b, 0, temp);
}
return true; } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
} public static void main(String[] args) {
FolderAllCopy.copyFile("D:\\info.sql", "d:\\srcll\\23\\ww1\\1.sql");
FolderAllCopy.copyFolder("D:\\Note", "D:\\srcll\\qq");
} }