You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java生成数组组合时按指定行数拆分输出多文件问题求助

问题根因

  • Java方法参数为值传递,combinationUtil方法内对局部变量bw重新赋值的操作,无法同步到上层递归调用的bw实例,程序全程都在使用初始化时关联第一个文件的Writer写入,所以其他新建的文件都为空。
  • 旧Writer仅执行flush未关闭,存在资源泄漏风险,极端情况会导致旧文件末尾内容丢失。
  • 全量组合生成后未关闭最终的Writer,最后一批不足1048575行的内容会残留在缓冲区无法落盘。

改造方案

  1. 用单元素数组包装BufferedWriter实例,所有递归层级共用同一个数组引用,修改数组内的Writer实例可全局生效。
  2. 每次切新文件前先关闭旧的Writer,保证旧文件内容完整写入。
  3. 递归结束后手动关闭最终的Writer,刷出剩余缓冲区内容。

修改后完整代码

package numbercombination2;
import java.io.*;

class NumberCombination2 {

    static void combinationUtil(int arr[], int data[], int start,
                                int end, int index, int r, long[] g, BufferedWriter[] bwArr, int[] count) throws IOException {
        if (index == r) {

            for (int j=0; j<r; j++)
                bwArr[0].write(data[j]+";");
            bwArr[0].newLine();
            count[0]++;

            if (count[0] % 1048575 == 0) {
                // 先关闭旧Writer,落盘全部内容
                bwArr[0].flush();
                bwArr[0].close();
                g[0]++;
                // 新建Writer写入数组,全局生效
                bwArr[0] = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Combinations - " + g[0] + ".txt")));
            }

            return;
        }

        for (int i=start; i<=end && end-i+1 >= r-index; i++) {
            data[index] = arr[i];
            combinationUtil(arr, data, i+1, end, index+1, r, g, bwArr, count);
        }
    }

    static void printCombination(int arr[], int n, int r, long[] g, BufferedWriter[] bwArr, int[] count) throws IOException {

        int data[]=new int[r];
        combinationUtil(arr, data, 0, n-1, 0, r, g, bwArr, count);
    }

    public static void main (String[] args)  throws IOException {
        int arr[] = {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};
        int r = 14;
        int n = arr.length;

        long[] g = new long[1];
        g[0] = 1;
        // 用数组包装Writer,实现全局修改生效
        BufferedWriter[] bwArr = new BufferedWriter[1];
        bwArr[0] = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Combinations - " + g[0] + ".txt")));
        int[] count = new int[]{0};

        printCombination(arr, n, r, g, bwArr, count);
        
        // 全部生成完成后关闭最后一个Writer,刷出剩余内容
        bwArr[0].flush();
        bwArr[0].close();
    }
}

内容的提问来源于stack exchange,提问作者JOAO12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:36:02