Search code examples
arraysfilewriterbufferedwriter

How to write an array using 'BufferedWriter' using a specific order in Java


I have an array like { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }. I want to write this array to a text file in the following order.

1 5 9
2 6 10
3 7 11
4 8 12

I have tried with following code. But I couldn't get output like this. I have a large data set and I want to write down them on a text file according to the above order.

public void writeFile() {

        try {
            File file = new File("D:/test.txt");
            file.createNewFile();

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);

            int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
            for (int i = 0; i < num.length; i++) {

                bw.write(String.valueOf(num[i]));
                bw.newLine();
            }
            bw.write('\n');
            System.out.println();
            bw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Solution

  • For this specific problem you might try a loop inside a loop, such as:

    for (int i = 0; i < 4; i++) {
        for (j = 0; j < num.length; j += 4) {
            bw.write(String.valueOf(num[i + j]) + ' ');
        }
        bw.newLine();
    }
    

    However, that works for the specific dataset you have. It's hard to know how to help further without knowing the specific problem you're trying to solve, such as how many lines to write and what to put on each line, but hopefully you get the idea and will be able to adapt it for your specific problem. Instead of hard-coding '4' as the loop control and increment amounts I'm guessing you might use 'div' or 'mod' operators to calculate what the '4' should really be.