Java读取文件的问题
我有一个文件,我们将其命名为text.txt。它包含几行文本。我试图用我的代码读取它,以便我可以使用我的代码编辑它,不幸的是,每当我尝试读取它时,它只是返回 null,并且根本不加载代码。没有错误消息或任何东西。
一个例子是一个包含以下内容的文件:
a
b
c
d
e
f
加载时,它加载以下内容:
a
b
c
d
null
这对我来说毫无意义,因为如果它进入 while 循环,它不应该退出!有人可以帮我吗?
try
{
File theFile = new File(docName);
if (theFile.exists() && theFile.canRead())
{
BufferedReader docFile;
docFile = new BufferedReader(
new FileReader(f));
String aLine = docFile.readLine();
while (aLine != null)
{
aLine = docFile.readLine();
doc.add( aLine );
}
docFile.close();
}
I have a file, let's call it text.txt. It contains a few lines of text. I am trying to read this in with my code so that I can edit it using my code, unfortunately whenever I try and read it, it simply returns null, and does not load the code at all. No error message or anything.
An example is a file with the following in it :
a
b
c
d
e
f
when loaded, it loads the following :
a
b
c
d
null
Which makes no sense to me whatsoever, since, if it is entering the while loop, it shouldn't be exiting! Can anyone help me out please ?
try
{
File theFile = new File(docName);
if (theFile.exists() && theFile.canRead())
{
BufferedReader docFile;
docFile = new BufferedReader(
new FileReader(f));
String aLine = docFile.readLine();
while (aLine != null)
{
aLine = docFile.readLine();
doc.add( aLine );
}
docFile.close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请注意,您正在阅读第一行
,然后通过
在循环内执行操作来丢弃该行。
Note that you are reading the first line with
and then you discard this line by doing
inside the loop.
在阅读下一行之前添加该行。如果你从逻辑上思考一下,这应该是有道理的,如果没有,请追问。
Add the line before reading the next line. If you think about this logically, it should make sense, and if not, please ask.
在 while 循环中,如果你翻转这两个语句,那么它会添加你知道不为空的行,然后检查下一行。现在的方式是,循环检查该行,然后前进一行并将新行添加到 doc 中,因此它可以为 null,然后在添加 null 后退出。
In the while loop, if you flip the two statements, then it will add the line you know is not null, then check the next line. The way you have it now, the loop checks the line, then advances a line and adds the new one to doc, so it can be null, then exit after adding null.