简体   繁体   English

如何读取整个文本文件并打印到数组中?

[英]How to read entire text file and print into an array?

I have a program that reads a text file which prints to the terminal and a new text file, but it reads the text file line by line.我有一个程序可以读取一个打印到终端的文本文件和一个新的文本文件,但它会逐行读取文本文件。 I want to edit the program so it reads the entire text file and prints the student names into an array.我想编辑程序,以便它读取整个文本文件并将学生姓名打印到数组中。

I'm assuming you're currently using something similar to this:我假设您目前正在使用类似的东西:

Scanner input = new Scanner(yourFile);

while (input.hasNextLine()) {
    System.out.println(input.nextLine());
}

To put the names into an array, change it to something like this:要将名称放入数组,请将其更改为如下所示:

Scanner input = new Scanner(yourFile);
ArrayList<String> names = new ArrayList<>();

while (input.hasNextLine()) {
    names.add(input.nextLine());
}

String[] nameList = names.toArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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