Getting a text file into a two dimensional ragged array in Java
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
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;
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!
If you use the Scanner class, you can keep calling nextInt()
For example (this is p-code ... you'll need to clean it up)
scanner = new Scanner(line);
while(scanner.hasNext())
list.add(scanner.nextInt())
row = list.toArray()
This of course isn't very optimized either.
instead of using .split() you could try using a StringTokenizer to split your lines up into just the numbers
Your parse is working fine when I tried it. both
line.split("\\s");
and
line.split(" ");
split the sample data into the right number of string elements. (I realize that the "\s" version is the better way to do this)
Here's a brute force way to convert the arrays to int arrays
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;
}
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;
}
精彩评论