获得一个文本文件转换成Java中的二维数组褴褛 [英] Getting a text file into a two dimensional ragged array in Java
问题描述
这是一个后续到<一个href=\"http://stackoverflow.com/questions/1724825/matlab-getting-an-array-of-cells-from-matlab-to-java\">my previous问题。我现在有这是此格式的文本文件:
Hey guys this is a followup to my previous question. I now have a text file which is formatted like this:
100 200
123
124 123 145
我想要做的就是让这些值在Java中的二维数组褴褛。
我到目前为止是这样的:
What I want to do is get these values into a two dimensional ragged array in Java. What I have so far is this:
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 [] []数组INT年底归还。
谢谢!
My problem here is that for example for the line 100 200 the variable "theline" has three elements {"100","","200"}
which it then passes on to rows with rows.add(theline)
What I want is to have just the numbers and if possible how to convert this String[][] array into an int[][] array int the end to return it.
Thanks!
推荐答案
确定这是基于什么奇闻趣事提出了解决方案:
OK this is a solution based on what Gonzo suggested:
public int[][] readFile(String fileName) throws FileNotFoundException, IOException {
String line = "";
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
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<Integer>());
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<list.size();i++){
data[i] = new int[list.get(i).size()];
for(int j=0;j<list.get(i).size();j++){
data[i][j] = (list.get(i).get(j));
}
}
return data;
}
这篇关于获得一个文本文件转换成Java中的二维数组褴褛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!