还可以写入多个文件夹目录,读取上传都可以
package com.esatcom.test;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import java.io.*;
import java.util.Objects;
import static org.springframework.util.FileCopyUtils.copy;
@Slf4j
public class upload {
//读取文件的路径
private static String readFilesPath = "C:\\task\\readpath";
//上传文件的路径
private static String writeFilesPath = "C:\\task\\writepath";
public static void main(String[] args) {
String[] readPathList = readFilesPath.split(",");
String[] writePathList = writeFilesPath.split(",");
int length = 0;
if (writePathList.length >= readPathList.length) {
length = readPathList.length;
} else if (writePathList.length < readPathList.length) {
length = writePathList.length;
}
for (int i = 0; i < length; i++) {
readAndWrite(readPathList[i], writePathList[i]);
}
}
private static void readAndWrite(String read, String write) {
log.info("读取文件START");
StopWatch stopWatch = new StopWatch();
stopWatch.start();
File file = new File(read);
if (file.isDirectory()) {
File[] filePathLists = file.listFiles();
for (int i = 0; i < Objects.requireNonNull(filePathLists).length; i++) {
if (filePathLists[i].isFile()) {
if (!new File(write).exists()) {
new File(write).mkdir();
//java中File类自带一个检测方法exists可以判断文件或文件夹是否存在,一般与mkdirs方法(该方法相较于mkdir可以创建包括父级路径,推荐使用该方法)或者createNewFile方法合作使用。
log.info("未获取到符合上传条件的文件目录,创建目录:" + new File(write).getName());
}
boolean upload = false;
try {
FileInputStream fis = new FileInputStream(filePathLists[i]);
FileOutputStream fos = new FileOutputStream(new File(write, filePathLists[i].getName()));
copy(fis, fos);
fis.close();
fos.close();
filePathLists[i].delete();
upload = true;
} catch (Exception e) {
e.printStackTrace();
log.info("上传文件异常");
}
if (upload) {
log.info("上传文件:" + filePathLists[i].getName() + "成功");
} else {
log.info("上传文件:" + filePathLists[i].getName() + "失败");
}
}
}
} else {
log.info("未获取到符合读取条件的文件目录");
}
stopWatch.stop();
log.info("读取并上传文件END,耗时:{} S", stopWatch.getTime());
}
}