简体   繁体   中英

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);
    }

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(" ")));
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM