2014-10-04 103 views
-1

我可能已找到解决方案:InputStream will not reset to beginning 如何将此代码实现到我的代码中? 我需要阅读的文本文件不止一次使用:如何多次读取文本文件

while (true){ 
final String checkUsername = brUsername.readLine(); 

if (checkUsername == null) { 

break; 
} 
if (checkUsername.equals(usernameInput)) { 
correctUsername = true; 
} 
} 

的读者和作家:

FileWriter fwUsername = new FileWriter("Username.txt", true); 
FileReader frUsername = new FileReader("Username.txt");// reads the created file Username.txt 
PrintWriter pwUsername = new PrintWriter(fwUsername, true); 
BufferedReader brUsername = new BufferedReader(frUsername); 

我不能做到这一点,而循环多次。没有错误,但while循环跳过。 1.我该如何重复这个循环? 2.如果我不能重复这个循环,我如何存储所有的值,以便我可以检查它? 3.此链接可能有解决方案,但我不知道如何做答案:How to reopen a file from a input stream。 我是初学者,所以我没有太多知识。我正在使用的代码:dropbox.com/s/du1u01f27t0ok2o/codehelp.txt?dl=0

+0

这将是很好,添加什么语言,你想这样做。 – Bas 2014-10-04 10:07:58

+0

读取文件后,您可以尝试'frUsername.reset()'将读取位置重置为文件的开头(或者最后一个设置为“mark”,但我猜这里没有)。 – Tom 2014-10-04 10:36:27

回答

0
frUsername = new FileReader("Username.txt"); 
brUsername = new BufferedReader(frUsername); 
while (true){ 
    final String checkUsername = brUsername.readLine(); 
    if (checkUsername == null) {break;} 
    if (checkUsername.equals(usernameInput)) {correctUsername = true;} 
} 
+0

我认为文本文件从顶部到底部读取,直到checkUsername == null。然后,当我尝试再读一遍checkUsername仍然等于null,然后它打破循环。 – lolftw 2014-10-04 10:26:12

+0

那么你的意思是你得到了一个好的迭代,然后是空的,还是从一开始就是空的?如果前者,你可以发布checkUsername包含的第一个轮到什么?无论哪种方式,我们可以看到输入文件的内容? frUsername为空吗? – 2014-10-04 10:40:06

+0

但是你仍然不应该在你知道为null的东西上调用equals()。 – 2014-10-04 10:41:39