要写一个copy的工具,目的是把两个版本git diff显示的发生变化的类拷贝到指定目录。
发现Files.lines很好用,就来记录一下
public static void main(String[] args) throws IOException {
final String form = args[0]; // 原文件位置
final String to = args[1]; // 拷贝位置
final String difftxt = args[2];
// 读取文本文件
log.info("---Start reading text file---");
List<String> list = Files.lines(Paths.get(difftxt), StandardCharsets.UTF_8).collect(Collectors.toList());
log.info("---The file has "+list.size()+" lines---");
list.forEach(e->{
log.info("---Start copying files: "+(list.indexOf(e)+1)+"---");
if (e.contains("/")){
int lastone = e.lastIndexOf("/"); //找到最后一个"/"的索引
String dir = e.substring(0, lastone);
// 创建文件夹
makeDir(to+dir);
}
copyFile(form+e,to+e);
});
}
// 拷贝文件
public static void copyFile(String oldPath, String newPath) {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
try (InputStream inStream = new FileInputStream(oldPath);
FileOutputStream fs = new FileOutputStream(newPath)) {
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
fs.write(buffer, 0, byteread);
}
} catch (Exception e) {
log.error("复制单个文件操作出错", e);
}
}
}
// 创建目录
public static void makeDir(String filename){
File file = new File(filename);
if(!file.exists()){//如果文件夹不存在
file.mkdirs();//创建文件夹
}
}
原来写的读取文本文件的方法
// 读取文本文件
public static ArrayList<String> toArrayByFileReader(String name) {
// 使用ArrayList来存储每行读取到的字符串
ArrayList<String> arrayList = new ArrayList<>();
try (FileReader fr = new FileReader(name);
BufferedReader bf = new BufferedReader(fr);) {
String str;
// 按行读取字符串
while ((str = bf.readLine()) != null) {
arrayList.add(str);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
// 返回数组
return arrayList;
}