如何将多行 StringBuilder 转换为字符数组?

How to convert a multi-line StringBuilder to a character array?

我的要求是在我做一个国际象棋问题时出现的,其中 8X8 个字符值是通过 System.in 给出的。我一直在测试它,我一直在提供 64 个输入,这非常困难。现在,我想将相同的内容保存在文本文件中并读取它并将其存储在字符数组中。请帮助我这样做。有多种方法可以读取和显示文件内容,或者我们可以将其转换为一维字符数组。但是,我想知道它可以直接从 StringBuilder 转换为二维字符数组!!!!这是我尝试过的。

StringBuilder c = new StringBuilder();
        File f = new File("file\input.txt");
        FileInputStream br = new FileInputStream(f);
        int str;
        while ((str = br.read()) != -1) {
            c.append((char) str);
        }
        br.close();
        System.out.println(c);

        int strBegin = 0;

        for (int i = 0; i < input.length; i++) {
            for (int j = 0; j < input.length; j++) {
                input[i][j] = c.substring(strBegin, strBegin + 1).toCharArray()[0];
                strBegin++;
            }
        }
        for (int i = 0; i < input.length; i++) {
            for (int j = 0; j < input.length; j++) {
                System.out.print(input[i][j] + " ");
            }
            System.out.println();
        }

此处,文件内容input.txt:

 2345678
1 345678
12 45678
123 5678
1234 678
12345 78
123456 8
1234567 

注意:有一个对角线 space 也必须存储到数组中。

当我 运行 代码时,我得到这个:

 2345678
1 345678
12 45678
123 5678
1234 678
12345 78
123456 8
1234567 
  2 3 4 5 6 7 8 

 1   3 4 5 6 
  8 
 1 2   4 
  6 7 8 
 1 2 
    5 6 7 8 

1 2 3 4   6 7 8 

 1 2 3 4 5   
  8 
 1 2 3 4 

建议你直接读整行,然后将其转换为字符数组,而不是一个字符一个字符地读取

public static char[][] readChessFile(String filename) throws IOException {
  char[][] input = new char[8][8];
  try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filename))) {

    String line;
    for (int i = 0; i < input.length; i++) {
      line = bufferedReader.readLine();
      if (line == null || line.length() != 8) {
        throw new IllegalStateException("File is not in correct format");
      }
      input[i] = line.toCharArray();
    }
  }
  return input;
}

这是我的测试代码

try {
  char[][] result = readChessFile(filename);
  for (int i = 0; i < result.length; i++) {
    for (int j = 0; j < result[i].length; j++) {
      System.out.print(result[i][j]);
    }
    System.out.println();
  }
} catch (IOException e) {
  e.printStackTrace();
}

这是一种方法。

我通过

分配两个d数组的第一部分
char[][] chars = new char[8][];

其余的将从字符串中分配。

      char[][] chars = new char[8][];
      try {
         BufferedReader br =
               new BufferedReader(new FileReader("input.txt"));
         String s;
         int i = 0;
         while ((s = br.readLine()) != null) {
           // assign the converted string array to chars[i]
            chars[i++] = s.toCharArray();
         }
         br.close();
      }
      catch (IOException ioe) {
         ioe.printStackTrace();
      }
      // now print them out, char by char.
      for (int i = 0; i < chars.length; i++) {
         for (int k = 0; k < chars[i].length; k++) {
            System.out.print(chars[i][k]);
         }
         System.out.println();
      }