【发布时间】:2017-04-14 18:08:44
【问题描述】:
我还在学习中,如果我有误解,请纠正我,但是 FileReader 对象不应该返回文本文件的全部内容吗?
我在这里有一个 sn-p 代码,我很简单地尝试获取一个短 .txt 文件的内容,并使用 system.out.println() 打印它
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
File testDoc = new File("C:\\Users\\Te\\Documents\\TestDocument.txt");
BufferedReader reader = new BufferedReader(new FileReader(testDoc));
Scanner in = new Scanner(new FileReader(testDoc));
try {
System.out.println(reader.readLine());
} finally {
reader.close();
}
}
}
.txt 文件只包含 3 行,格式如下:
some text here, more text and stuff
new estonian lessons
word = new word
但是程序只打印文件中的第一行。
some text here, more text and stuff
这是什么原因造成的,我该如何纠正?
我已尝试阅读文档,并通过 Stackoverflow 进行搜索,但我无法找到解决此问题的方法。
【问题讨论】:
-
你不会错过某种循环吗? (请注意,有更多现代方式来读取文本文件)
-
readLine()就是这样做的,只读取 1 行 - 这并不意味着readFile()。你说你读过documentation,但我觉得这很难相信,因为文档的第一行声明“读取一行文本”,然后继续定义什么是一行文本。 -
那是因为您只调用了一次
readLine。为什么您会期望读取整个文件? -
@shawn FileReader 不会读取文件的全部内容。实际考虑一下,如果文件很大并且 FileReader 读取整个文件,那么我们将开始遇到内存问题。
-
@RC。你会推荐什么?我的知识有限,我只是在一个关于异常和错误处理的演示中使用 readLine()
标签: java bufferedreader filereader