madhaj1
madhaj1

Reputation: 35

Java read text file in lines, but seperate words in lines into array

I am trying to write a code that looks at a text file, and does a while loop so that it reads each line, but I need each word per line to be in an array so I can carry out some if statements. The problem I am having at the moment is that my array is currently storing all the words in the file in an array.. instead of all the words per line in array.

Here some of my current code:

    public static void main(String[] args) throws IOException {

    Scanner in = new Scanner(new File("test.txt"));
    List<String> listwords = new ArrayList<>();


while (in.hasNext()) {
      listwords.addAll(Arrays.asList(in.nextLine().split(" ")));
}


    if(listwords.get(4) == null){
        name = listwords.get(2);
     }
    else {
        name = listwords.get(4);
    }

Upvotes: 0

Views: 1770

Answers (2)

modmoto
modmoto

Reputation: 3280

You can use

listwords.addAll(Arrays.asList(in.nextLine().split("\\r?\\n")));

to split on new Lines. Then you can split these further on the Whitespace, if you want.

Upvotes: 1

janos
janos

Reputation: 124656

If you want to have an array of strings per line, then write like this instead:

List<String[]> listwords = new ArrayList<>();

while (in.hasNext()) {
    listwords.add(in.nextLine().split(" "));
}

Btw, you seem to be using the term "array" and "ArrayList" interchangeably. That would be a mistake, they are distinct things.

If you want to have an List of strings per line, then write like this instead:

List<List<String>> listwords = new ArrayList<>();

while (in.hasNext()) {
    listwords.add(Arrays.asList(in.nextLine().split(" ")));
}

Upvotes: 2

Related Questions