I read this thread, but, how can I put text from a file dynamically into multidimensional array?
Data like:
1,4,5,7,nine
11,19
22,twenty-three,39
30,32,38
..
..
I read this thread, but, how can I put text from a file dynamically into multidimensional array?
Data like:
1,4,5,7,nine
11,19
22,twenty-three,39
30,32,38
..
..
You could do something like:
try {
ArrayList<List<String> > matrix = new ArrayList<List<String> >();
FileInputStrem iStream = new FileInputStream("path/to/file");
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = reader.readLine();
while(line != null){
line = reader.readLine();
matrix.add(Arrays.asList(line.split(",")));
}
} catch (Exception e) {
// handle exception
} finally {
reader.close();
istream.close();
}
One of the biggest advantage of ArrayList over array is that ArrayList is dynamic in size and it is amortized constant to add to the end.
To answer your comment, to remove:
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix.get(i).size(); j++) {
if (someCondition) // determine which to remove
matrix.get(i).remove(j);
}
}
Use a class such as BufferedReader to read each line from the file. Use a scanner on each line to get the individual tokens.
Scanner scanner = new Scanner(currentLineInFile);
scanner.useDelimiter(",");
while (scanner.hasNext())
{
String token = scanner.next(); // Only call this once in the loop.
if (token.isEmpty())
{
// This case trips when the string "this,is,,a,test" is given.
// If you don't want empty elements in your array, this is where
// you need to handle the error.
continue; // or throw exception, Log.d, etc.
}
// Do something with the token (aka. add it to your array structure.
}
If you couple this to the array structure will allow you to handle data on demand (like from a web service.) This implementation accounts for cases with two ',' next to each other. You can handle these empty elements as you read them. Using String.split will leave these empty elements in the array which you'll have to handle later.