Files.lines读取文本文件从一串到一行

要写一个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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值