在Java中将文本文件转换为二维不规则数组

嘿伙计们这是我上一个问题的后续内容。 我现在有一个文本文件格式如下:

100 200 123 124 123 145 

我想要做的是将这些值放入Java中的二维不规则数组中。 到目前为止我所拥有的是:

 public String[][] readFile(String fileName) throws FileNotFoundException, IOException { String line = ""; ArrayList rows = new ArrayList(); FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); while((line = br.readLine()) != null) { String[] theline = line.split("\\s");//TODO: Here it adds the space between two numbers as an element rows.add(theline); } String[][] data = new String[rows.size()][]; data = (String[][])rows.toArray(data); //In the end I want to return an int[][] this a placeholder for testing return data; 

我的问题在于,例如对于行100 200,变量“theline”有三个元素{"100","","200"}然后它传递给包含rows.add(theline)行我想要的是只有数字,如果可能的话,如何将这个String [] []数组转换为int [] []数组,最后返回它。 谢谢!

如果您使用Scanner类,则可以继续调用nextInt()

例如(这是p代码……你需要清理它)

 scanner = new Scanner(line); while(scanner.hasNext()) list.add(scanner.nextInt()) row = list.toArray() 

这当然也没有非常优化。

而不是使用.split(),你可以尝试使用StringTokenizer将你的行分成几个数字

我尝试时你的解析工作正常。 都

  line.split("\\s"); 

  line.split(" "); 

将示例数据拆分为正确数量的字符串元素。 (我意识到“\ s”版本是更好的方法)

这是将数组转换为int数组的powershell方法

 int [][] intArray = new int[data.length][]; for (int i = 0; i < intArray.length; i++) { int [] rowArray = new int [data[i].length]; for (int j = 0; j < rowArray.length; j++) { rowArray[j] = Integer.parseInt(data[i][j]); } intArray[i] = rowArray; } 

好的,这是一个基于奇闻趣事建议的解决方案:

 public int[][] readFile(String fileName) throws FileNotFoundException, IOException { String line = ""; ArrayList> list = new ArrayList>(); FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); int r = 0, c = 0;//Read the file while((line = br.readLine()) != null) { Scanner scanner = new Scanner(line); list.add(new ArrayList()); while(scanner.hasNext()){ list.get(r).add(scanner.nextInt()); c++; } r++; } //Convert the list into an int[][] int[][] data = new int[list.size()][]; for (int i=0;i