Java将文件读入ArrayList? [英] Java reading a file into an ArrayList?

查看:520
本文介绍了Java将文件读入ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中将文件内容读入 ArrayList< String>

How do you read the contents of a file into an ArrayList<String> in Java?

以下是文件内容:

cat
house
dog
.
.
.

只需将每个单词读入 ArrayList 即可。

Just read each word into the ArrayList.

推荐答案

这个java代码读入每个单词并将其放入ArrayList:

Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
    list.add(s.next());
}
s.close();

使用 s.hasNextLine() s.nextLine()如果你想逐行而不是逐字阅读。

Use s.hasNextLine() and s.nextLine() if you want to read in line by line instead of word by word.

这篇关于Java将文件读入ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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