Jason Liu Jason Liu - 2 months ago 13
Java Question

Converting a .txt file to a 2D arraylist of strings

So I'm trying to convert a .txt file in the format of

1 2 3 4
5 6 7 8
9 1 0 1


into a 2D arraylist of strings.
This should also be replicable with any other thing such as

EXTENDING RETRACTING RETRACTING EXTENDING
EXTENDING EXTENDING RETRACTING
RETRACTING


Here's my code

public class Test {
public static ArrayList<ArrayList<String>> readFromFile(String path) throws FileNotFoundException{
@SuppressWarnings("resource")
Scanner in = new Scanner(new File(path));
ArrayList<ArrayList<String>> comments= new ArrayList<ArrayList<String>>();
ArrayList<String> words = new ArrayList<String>();
String[] line;
String str;
String [] values;
while(in.hasNextLine()){
str=in.nextLine();
line = str.split("\t");
values = line[2].split(" ");
for(String word : values){
words.add(word);
}
}
comments.add(words);
return comments;
}

public static void main(String[] args) throws FileNotFoundException{
ArrayList<ArrayList<String>> inputs = readFromFile("/Users/Jason/yaw.txt");
int k = 0;
for(int i = 0; i < inputs.size(); i++){
for(int j = 0; j < inputs.get(k).size(); j++){
System.out.print(inputs.get(i).get(j));
k++;
}
System.out.println();
}
}
}


Currently, it returns this error.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Test.readFromFile(Test.java:19)
at Test.main(Test.java:31)


Any help on how to get this working?

Answer

This is one way to solve it:

    // read file into list
    List<String> linesInFile = Files.readAllLines(Paths.get("filename.txt"));
    // create 2d array based on number of lines
    List<List<String>> array = new ArrayList<>(linesInFile.size());

    // iterate through every line of the file and split the elements using whitespace
    linesInFile.forEach(line -> {
        // get the elements in the current line
        String[] elements = line.split("\\s+");
        // store it in our 2d array
        array.add(Arrays.asList(elements));
    });

    // print every row in our 2d array
    array.forEach(System.out::println);

The Files.readAllLines method will return a List with all the lines in your file (similar to what your own version does).