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
java: how to read a txt file to an Array of strings
提问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.Scanner
and java.util.List
.
使用java.util.Scanner
和java.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
This will get you a List
of String
. You can use List.toArray()
to convert, but I'd suggest staying with List
.
这将让你List
的String
。您可以使用List.toArray()
来转换,但我建议继续使用List
.
回答by crazyscot
Set up a BufferedReader
to read from the file, then pick up lines from from the buffer however many times.
设置 aBufferedReader
以从文件中读取,然后从缓冲区中多次提取行。