Java按行读取文本文件,但将行中的单词分开到数组中 [英] Java read text file in lines, but seperate words in lines into array

查看:25
本文介绍了Java按行读取文本文件,但将行中的单词分开到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个查看文本文件的代码,并执行 while 循环以读取每一行,但我需要将每行的每个单词都放在一个数组中,以便我可以执行一些 if 语句.我目前遇到的问题是我的数组当前将文件中的所有单词存储在一个数组中..而不是数组中每行的所有单词.

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

推荐答案

如果你想每行有一个 array 字符串,那么写成这样:

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

顺便说一句,您似乎交替使用术语数组"和ArrayList".那将是一个错误,它们是不同的东西.

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

如果你想每行有一个 List 字符串,那么写成这样:

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

这篇关于Java按行读取文本文件,但将行中的单词分开到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆