在StringBuilder中分隔行

时间:2018-08-10 19:41:16

标签: java stringbuilder

我正在学习Java,但是碰巧在以矩阵形状在文本文件上编写2D_array时遇到问题;即每一行都在单独的行上。

MWE:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class Lect14_Arrays {

    public static void main(String[] args) throws FileNotFoundException {
        int supNode = 4;
        int demNode = 4;
        int goods = 3;

        int[][][] Q = new int[supNode][demNode][goods];
        int[][] gDem = new int[demNode][goods];

        Scanner in = new Scanner(new BufferedReader(new FileReader("Q.txt")));
        while (in.hasNextLine()) {
            for (int i = 0; i < Q.length; i++) {
                for (int j = 0; j < Q[0].length; j++) {
                    String[] line = in.nextLine().trim().split(" ");
                    for (int g = 0; g < line.length; g++) {
                        Q[i][j][g] = Integer.parseInt(line[g]);
                    }
                }
            }
        }

        for (int j = 0; j < Q[0].length; j++) {
            for (int i = 0; i < Q.length; i++) {
                for (int g = 0; g < goods; g++) {
                    gDem[j][g] += Q[i][j][g];
                }
            }
        }

        File gdFile = new File("gDem.txt");
        StringBuilder sB4 = new StringBuilder();
        try (BufferedWriter br4 = new BufferedWriter(new FileWriter(gdFile))) {
            for (int j = 0; j < gDem.length; j++) {
                for (int g = 0; g < gDem[0].length; g++) {
                    sB4.append(gDem[j][g]).append(" ");
                }
            }
            br4.write(sB4.toString().trim());
            br4.close();
        } catch (IOException e) {
            System.out.println("Unable to write : " + gdFile.toString());
        }
    }
}

Q [] [] []矩阵如下保存在Q.txt文件中:

3 3 4 
10 8 2
4 3 3
9 5 16
2 1 2
0 3 0 
1 2 1
12 12 12
0 1 3 
1 7 1 
1 1 6 
9 9 14
8 4 0 
2 5 0 
7 6 7 
9 9 9

并将gDem写入gDem.txt文件,如下所示:

13 9 9 13 23 3 13 12 17 39 35 51

我的问题是如何编写和保存gDem的内容,如下所示:

13 9 9 
13 23 3
13 12 17
39 35 51

非常感谢您的回答。

关于, 博尔尼

2 个答案:

答案 0 :(得分:2)

如果您想在sB4中使用换行符,则应添加换行符,即

sB4.append(System.lineSeparator());

答案 1 :(得分:2)

StringBuilder中将每个添加完后,必须添加换行符

for (int j = 0; j < gDem.length; j++) {
    for (int g = 0; g < gDem[0].length; g++) {
        sB4.append(gDem[j][g]).append(" ");
    }
    sB4.append(System.lineSeparator());//add new line to move to next row
}