Java:如何将文本文件读取到字符串数组中

12

你好,我想读取一个有N行的txt文件,并将其结果放入一个字符串数组中。


3
现在我们知道了你想要什么,你有什么问题? :) - OscarRyz
1
这里有一些替代方案(只需要稍加修改)https://dev59.com/qnRC5IYBdhLWcg3wVvnL - OscarRyz
还有一个:http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html - OscarRyz
4个回答

30

使用 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]);

1
这是答案,谢谢! - Enrique San Martín
3
@Enrique:阅读有关 Scanner 如何处理 IOException 的 API。 - polygenelubricants
如何打印String[] arr的所有元素? - Chinmoy
你可以使用for循环遍历数组,在Eclipse中,你可以使用自动完成功能,例如:https://ideone.com/ZMTesT - Enrique San Martín

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

apache commons-io获取这将会给你一个ListString。你可以使用List.toArray()进行转换,但我建议保持使用List


1
看起来这个方法现在已经被弃用了。 - Praveen Kumar

2

你读过Java教程吗?

例如:

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();
}

1
是的,我读过Java教程和其他书籍,但这并不能解决问题,因为我想把文件中的所有行放入一个字符串数组中,例如:String[] content = new String[length_of_the_string]; int i = 0; while ((line = reader.readLine()) != null) { content[i] = line; i++; } - Enrique San Martín

-1

建立一个BufferedReader来从文件中读取,然后从缓冲区中获取行数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接