Java分割文本文件,按文件数、行数均分

Java分割文本文件,按需要分割成的文件数分割,也可按行数分割。

 /**
     * 按行分割文件
     *
     * @param sourceFilePath      为源文件路径
     * @param targetDirectoryPath 文件分割后存放的目标目录
     * @param number              切割成多少个文件
     */
    public static List<String> splitFileByLine(String sourceFilePath, String targetDirectoryPath, int number) throws IOException {
        //源文件名
        String sourceFileName = sourceFilePath
                .substring(sourceFilePath.lastIndexOf(File.separator) + 1, sourceFilePath.lastIndexOf("."));
        //切割后的文件名
        String splitFileName = targetDirectoryPath + File.separator + sourceFileName + "-%s.csv";
        File targetDirectory = new File(targetDirectoryPath);
        if (!targetDirectory.exists()) {
            targetDirectory.mkdirs();
        }

        List<String> resultFileNames = Lists.newArrayList();
        //字符输出流
        PrintWriter pw = null;
        String tempLine;
        //本次行数累计 , 达到rows开辟新文件
        int lineNum = 0;
        //当前文件索引
        int splitFileIndex = 1;
        //每个文件行数
        long lines = Files.lines(Paths.get(sourceFilePath)).count();
        int rows = (int) Math.ceil(1.0 * lines / number);

        log.info("原文件行数:{}, 新文件行数:{}", lines, rows);

        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFilePath)))) {
            String parsedFileName = String.format(splitFileName, splitFileIndex);
            pw = new PrintWriter(parsedFileName);
            resultFileNames.add(parsedFileName);
            while ((tempLine = br.readLine()) != null) {
                //需要换新文件
                if (lineNum > 0 && lineNum % rows == 0) {
                    pw.flush();
                    pw.close();
                    parsedFileName = String.format(splitFileName, ++splitFileIndex);
                    pw = new PrintWriter(parsedFileName);
                    resultFileNames.add(parsedFileName);
                }
                pw.write(tempLine + "\n");
                lineNum++;
            }
            log.info("返回文件列表:{}", resultFileNames.toString());
            return resultFileNames;
        } catch (Exception e) {
            log.error("切割文件异常:{}", e);
        } finally {
            if (null != pw) {
                pw.flush();
                pw.close();
            }
        }
        return resultFileNames;
    }

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值