1 主方法
public static void main(String[] args) {
List<File> fileList = new ArrayList<>();
JavaFileUtils.getAllFiles("文件源地址", fileList);
if (!JavaListUtils.isEmpty(fileList)) {
for (File file : fileList) {
JavaFileUtils.cpFileToObj(file, "文件拷贝地址");
}
}
}
2 递归将目录下的所有文件查找出来
public final static String linux = "/";
public static void getAllFiles(String souceAddress, List<File> fileList) {
if (souceAddress == null || "".equals(souceAddress.trim()) || fileList == null) {
log.info("入参为空souceAddress:{},fileList:{}", souceAddress, fileList);
return;
}
try {
File file = new File(souceAddress);
if (file == null) {
log.info("入参为空");
return;
}
if (!file.isDirectory()) {
fileList.add(file);
} else {
String[] list = file.list();
if (list == null || list.length <= 0) {
return;
}
for (String souceAddressStr : list) {
try {
File fileIn = new File(souceAddress + ThirdServiceImpl.linux + souceAddressStr);
if (!fileIn.isDirectory()) {
fileList.add(fileIn);
} else {
getAllFiles(souceAddress + ThirdServiceImpl.linux + souceAddressStr, fileList);
}
} catch (Exception e) {
log.info("出错了souceAddressStr:{},souceAddress:{}", souceAddressStr, souceAddress);
}
}
}
} catch (Exception e) {
log.info("外部出错了souceAddress:{}", souceAddress);
}
return;
}
3 将文件集体拷贝到指定目录
public static void cpFileToObj(File file, String objectAddress) {
if (file == null) {
log.info("文件名:{}", file.getName());
log.info("文件路径getAbsolutePath:{}", file.getAbsolutePath());
return;
}
log.info("文件名开始:{}", file.getName());
log.info("文件路径getAbsolutePath:{}", file.getAbsolutePath());
try {
FileInputStream fileInputStream = new FileInputStream(file);
String objectAddressStr = objectAddress + ThirdServiceImpl.linux + file.getParentFile().getName() + "-" + file.getName();
log.info("复制的文件名开始:{}", objectAddressStr);
FileOutputStream fileOutputStream = new FileOutputStream(new File(objectAddressStr));
try {
byte datas[] = new byte[1024 * 8];
int len = 0;
while ((len = fileInputStream.read(datas)) != -1)
{
fileOutputStream.write(datas, 0, len);
}
} catch (FileNotFoundException e) {
log.error("内层文件拷贝出错");
}
log.info("复制的文件名结束:{}", objectAddressStr);
fileInputStream.close();
fileOutputStream.close();
log.info("复制的文件名释放资源结束:{}", objectAddressStr);
} catch (FileNotFoundException e) {
log.error("文件拷贝出错");
} catch (IOException e) {
e.printStackTrace();
}
log.info("文件名结束:{}", file.getName());
}