java:如何将txt文件读取到字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2977075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:09:47  来源:igfitidea点击:

java: how to read a txt file to an Array of strings

java

提问by Enrique San Martín

Hi i want to read a txt file with N lines and the result put it in an Array of strings.

嗨,我想读取一个包含 N 行的 txt 文件,结果将它放入一个字符串数组中。

采纳答案by polygenelubricants

Use a java.util.Scannerand java.util.List.

使用java.util.Scannerjava.util.List

Scanner sc = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
  lines.add(sc.nextLine());
}

String[] arr = lines.toArray(new String[0]);

回答by JRL

Have you read the Java tutorial?

你读过Java教程吗?

For example:

例如:

Path file = ...;
InputStream in = null;
try {
    in = file.newInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException x) {
    System.err.println(x);
} finally {
    if (in != null) in.close();
}

回答by Bozho

FileUtils.readLines(new File("/path/filename"));

From apache commons-io

来自apache commons-io

This will get you a Listof String. You can use List.toArray()to convert, but I'd suggest staying with List.

这将让你ListString。您可以使用List.toArray()来转换,但我建议继续使用List.

回答by crazyscot

Set up a BufferedReaderto read from the file, then pick up lines from from the buffer however many times.

设置 aBufferedReader以从文件中读取,然后从缓冲区中多次提取行。