• java分割大文件为多个小文件


    需求:

    如果你希望每读取到5000行数据时,就生成一个新的文件,并在每个新文件中继续写入接下来的5000行,你可以稍微修改上面的代码。下面是如何做到这一点的步骤和示例代码:

    1、初始化一个行计数器来跟踪已经读取的行数。
    2、在循环中读取输入文件的每一行。
    3、对于每一行,如果行计数器是5000的倍数,则关闭当前的输出文件流并打开一个新文件用于写入。
    4、将处理过的行写入当前活动的输出文件。
    更新行计数器。
    5、重复步骤2-5,直到文件结束。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    public static void main(String[] args) {
            String inputFile = "input.txt"; // 输入文件路径
            int linesPerFile = 5000; // 每5000行创建一个新文件
    
            int lineCount = 0;
            int fileCount = 1;
            BufferedReader reader = null;
            BufferedWriter writer = null;
    
            try {
                reader = new BufferedReader(new FileReader(inputFile));
                // 创建第一个输出文件
                writer = new BufferedWriter(new FileWriter("output_" + fileCount + ".txt"));
    
                String line;
                while ((line = reader.readLine()) != null) {
                    writer.write("Processed: " + line);
                    writer.newLine(); // 写入换行符
                    lineCount++;
    
                    if (lineCount % linesPerFile == 0) {
                        // 关闭当前文件并打开新文件
                        writer.close();
                        fileCount++;
                        writer = new BufferedWriter(new FileWriter("output_" + fileCount + ".txt"));
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
  • 相关阅读:
    查看系统的核心信息
    githubPage部署Vue项目
    AUTOSAR汽车电子嵌入式编程精讲300篇-车载网络 CAN 总线报文异常检测
    [vue] 嵌套iframe,$router.go(-1)后退bug
    【AI视野·今日Robot 机器人论文速览 第四十八期】Thu, 5 Oct 2023
    Apache Echarts介绍与入门
    想要进入IB国际学校,这些证书你要知道
    数据库基本概念
    闭包和装饰器
    证书显示未受信任,生成的证书过期
  • 原文地址:https://blog.csdn.net/weixin_48811255/article/details/136643105