最近在做全链路压力测试,涉及到风控OCR的校验,需要造一些数据,每次发起交易,系统会去读取文件夹里的OCR数据(有这个格式的数据就行,数据不需要和人名匹配,这个校验被我mock掉了)
需要造的数据是:10万个文件夹,内含OCR数据文件如图所示,可以从一个现有文件夹copy。
现在已经换成了org.apache的FileUtils方法,又快又简单,10万条大概几十分钟造完了,下面那个调cmd的10多个小时才弄完(捂脸)
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class FolderCopy {
public static void copy(String from ,String to) {
File file = new File(to);
if (!file.exists()) {
file.mkdirs();
}
try {
FileUtils.copyFileToDirectory(new File(from),new File(to));
}catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
for(int i=0;i<100000;i++) {
long a = 189200001+i;
for(int j=1;j<4;j++) {
String from = "D:\\20201205\\ocr\\189200000\\"+j+".txt";
String to = "D:\\20201205\\ocr\\"+a;
FolderCopy.copy(from, to);
}
}
}
}
找了一些Java复制文件的代码,基本上都是输入输出流操作,而且有的错误很多,试了下在window下调试需要挺长时间,于是另辟蹊径,想想调了Runtime 这个偷懒又简单的办法,代码如下:
public class FolderCopy {
public static void copy(String from ,String to) {
File file = new File(to);
if (!file.exists()) {
file.mkdirs();
}
String cmd = "cmd /c xcopy /Y "+from+" "+to;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(cmd);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]) {
for(int i=0;i<100000;i++) {
long a = 189000001+i;
String from = "D:\\test\\20201205\\ocr\\189000000";
String to = "D:\\test\\20201205\\ocr\\"+a;
FolderCopy.copy(from, to);
}
}
}
还行,不太占资源哈哈哈
就是速度比较感人。。。又不是不能用XD
最后放个正常复制文件和文件夹的代码:
public static void copyDir(String sourcePath, String newPath) throws IOException {
File file = new File(sourcePath);
String[] filePath = file.list();
if (!(new File(newPath)).exists()) {
(new File(newPath)).mkdir();
}
for (int i = 0; i < filePath.length; i++) {
if ((new File(sourcePath + file.separator + filePath[i])).isDirectory()) { copyDir(sourcePath + file.separator + filePath[i], path + file.separator + filePath[i]); } if (new File(sourcePath + file.separator + filePath[i]).isFile()) { copyFile(sourcePath + file.separator + filePath[i], path + file.separator + filePath[i]); }
}
}
public static void copyFile(String oldPath, String newPath) throws IOException {
File oldFile = new File(oldPath);
File file = new File(newPath);
FileInputStream in = new FileInputStream(oldFile);
FileOutputStream out = new FileOutputStream(file);;
byte[] buffer=new byte[2097152];
int readByte = 0;
while((readByte = in.read(buffer)) != -1){
out.write(buffer, 0, readByte);
}
in.close();
out.close();
}