逐行读取文本文件到字符串中

Car*_*tem 0 java arrays string line

如何在String不使用BufferedReader?的情况下逐行读取文本文件的内容?

例如,我有一个看起来像这样的文本文件:

Purlplemonkeys
greenGorilla
Run Code Online (Sandbox Code Playgroud)

我想创建两个strings,然后使用这样的东西

File file = new File(System.getProperty("user.dir") + "\Textfile.txt");
String str = new String(file.nextLine());
String str2 = new String(file.nextLine());
Run Code Online (Sandbox Code Playgroud)

这样它就分配str了值"Purlplemonkeys"str2"greenGorilla".

小智 5

您应该使用ArrayList.

File file = new File(fileName);
Scanner input = new Scanner(file);
List<String> list = new ArrayList<String>();

while (input.hasNextLine()) {
    list.add(input.nextLine());
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以从其索引访问列表中的一个特定元素,如下所示:

System.out.println(list.get(0));
Run Code Online (Sandbox Code Playgroud)

这会给你第一行(即:Purlplemonkeys)


Rus*_*tam 5

您可以阅读要列出的文本文件:

List<String> lst = Files.readAllLines(Paths.get("C:\\test.txt"));
Run Code Online (Sandbox Code Playgroud)

然后根据需要访问每一行

PS文件 - java.nio.file.Files