简体   繁体   English

如何将文本文件转换为多维字符串数组

[英]How to convert a text file into multidimensional string array

This is my sample text file: 这是我的示例文本文件:

128_1   128_2   128_3   128_4   128_5   128_6   128_7   128_8
256_1   256_2   256_3   256_4   256_5   256_6   256_7   256_8
512_1   512_2   512_3   512_4   512_5   512_6   512_7   512_8

I am trying to convert this text file into 2d string array but cant get it right. 我正在尝试将此文本文件转换为2d字符串数组,但无法正确处理。 I end up with Null values. 我最终得到了Null值。

This is the output of my code when i run: 这是我运行时代码的输出:

128_1 128_2 128_3 128_4 128_5 128_6 128_7 128_8
256_1 256_2 256_3 256_4 256_5 256_6 256_7 256_8
512_1 512_2 512_3 512_4 512_5 512_6 512_7 512_8
null null null null null null null null
null null null null null null null null
null null null null null null null null
null null null null null null null null
null null null null null null null null

This is what i have so far: 这是我到目前为止所拥有的:

String[][] multi() {

  String[][] tobeReturned = null;
  BufferedReader reader = createReader("/numbers/_output.txt");

  String line;
  int row = 0;
  int size = 0;

  try {
    while ((line = reader.readLine()) != null) {
      String[] vals = line.trim().split("\t");

      if (tobeReturned == null) {
        size = vals.length;
        tobeReturned = new String[size][size];
        //println(size);
      }

      for (int col = 0; col < size; col++) {
        tobeReturned[row][col] = vals[col];
      }

      row++;     

      //println(row);
    }
  }
  catch(IOException e) {
  }

  for (String[] arr : tobeReturned) {
    println(arr);
  }

  return tobeReturned;
}

As said by previous your sizing is wrong. 如前所述,您的尺码错误。 You know the size of the file so try this: 您知道文件的大小,因此请尝试以下操作:

 row=0;
 tobeReturned = new String[3][8];
 while ((line = reader.readLine()) != null) {
  String[] vals = line.trim().split("\t");
  for (int col = 0; col < 8; col++) {
   tobeReturned[row][col] = vals[col];
 }
 row++;  
 }
 for(i=0; i<3; i++){
  for(j=0;j<8; j++){
   printlin(tobeReturned[i][j];
  }
 }   

String array creation is in error. 字符串数组创建错误。

tobeReturned = new String[size][size];

This should be like 这应该像

tobeReturned = new String[row][col];

Since, at first, you didn't count how many rows there are, you create a square matrix of column length. 因为起初您没有计算行数,所以创建了一个列长的方阵。

If you really need to use String[][] you should also count the lines. 如果确实需要使用String[][]还应该计算行数。

If you are using Java 8, I suggest you the following implementation: 如果您使用的是Java 8,建议您执行以下实现:

public static String[][] strMatrix(String filePath) throws IOException {
        Stream<String> lines = Files.lines(Paths.get(filePath));
        String[][] strMat = lines.map(line -> line.split("\\s+")).toArray(String[][]::new);
        return strMat;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM