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

耗尽温柔 提交于 2020-01-14 06:05:51

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/47618420/java-read-text-file-in-lines-but-seperate-words-in-lines-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!