用Java从文本文件制作列表
在Java中,我使用Scanner
来读取文本文件,
例如(猫、狗、老鼠)。
当我使用System.out.println()
时,输出看起来像cat, dog, mouse
我希望列表是这样的
cat
dog
mouse
下面有帮助代码吗
Scanner scan = null;
Scanner scan2 = null;
boolean same = true;
try {
scan = new Scanner(new
File("//home//mearts//keywords.txt"));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
List<String> firstLines = new ArrayList<String>();
while (scan.hasNextLine()) {
firstLines.add(scan.nextLine());
System.out.println(firstLines);
}
# 1 楼答案
尝试以下方法:
顺便说一句,由于您只阅读了几行,您可能还想看看java.nio.file.Files:
# 2 楼答案
您正在逐行读取文件,而不是考虑分隔符: