简体   繁体   English

Java无法读取文本文件中的其他行

[英]Java unable to read other lines in text file

Showing my current progress显示我目前的进度

I am unable to make the program read more than the first line of text in s.dat in this case.在这种情况下,我无法让程序读取超过 s.dat 中的第一行文本。

Is there anything that I am missing?有什么我想念的吗? Any help is greatly appreciated.任何帮助是极大的赞赏。

Try something like this:尝试这样的事情:

    //get the file location
    String filePath = "somefilepath.txt";

    //catch file IO errors
    try {
        //return the contents of the file
        String[] lines = Files.readAllLines(Paths.get(filePath))
    }

It will assign to the variable lines an array of all the string lines in the file.它将为变量 lines 分配文件中所有字符串行的数组。 Then you can index into that array to get what you need or loop through it.然后您可以对该数组进行索引以获取您需要的内容或循环遍历它。

EDIT: to do it without arrays see this link:编辑:要在没有数组的情况下执行此操作,请参阅此链接:

http://www.programcreek.com/2011/03/java-read-a-file-line-by-line-code-example/ http://www.programcreek.com/2011/03/java-read-a-file-line-by-line-code-example/

您正在做 if ..else 语句错误 在这两种情况下,您都将返回函数或中断循环,您将在第一次执行后终止循环,这就是发生这种情况的原因。

Your while loop reads (approximately):您的 while 循环读取(大约):

while ( more lines ) {
     if ( match ) {
          return;
     } else {
          break;
     }
 }

Your loop will never execute more than once.您的循环永远不会执行多次。

Remove the else clause, and put the println("Not found");删除else子句,并放入println("Not found"); after the loop finishes.循环结束后。

Your code will only read the first line as you have placed return in if block and break in else block.您的代码只会读取第一行,因为您已将 return 放入 if 块并中断 else 块。 It will come out of loop in both the cases.在这两种情况下它都会跳出循环。

Remove the return statement from the if block.从 if 块中删除 return 语句。

your else clause is wrong, if the first loop doesn't match, it's immediately exit while and doesn't do anything else.你的 else 子句是错误的,如果第一个循环不匹配,它会立即退出 while 并且不做任何其他事情。 you should print the statement "Not found .... " after while loop end.您应该在 while 循环结束后打印语句“Not found ....”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM