正确使用while循环中的BufferedReader.readLine()
所以我在将一个文本文件读入我的程序时遇到了问题。 这是代码:
try{ InputStream fis=new FileInputStream(targetsFile); BufferedReader br=new BufferedReader(new InputStreamReader(fis)); //while(br.readLine()!=null){ for(int i=0;i<100;i++){ String[] words=br.readLine().split(" "); int targetX=Integer.parseInt(words[0]); int targetY=Integer.parseInt(words[1]); int targetW=Integer.parseInt(words[2]); int targetH=Integer.parseInt(words[3]); int targetHits=Integer.parseInt(words[4]); Target a=new Target(targetX, targetY, targetW, targetH, targetHits); targets.add(a); } br.close(); } catch(Exception e){ System.err.println("Error: Target File Cannot Be Read"); }
我正在读取的文件是100行参数。 如果我使用for循环它完美地工作。 如果我使用while语句(for循环上方注释掉的那个),它会在50处停止。用户有可能使用任意行数的文件运行程序,因此我当前的for循环实现赢了工作。
为什么while(br.readLine()!=null)
停在50? 我检查了文本文件,没有任何东西可以挂起来。
当我使用while循环时,我没有从try-catch中得到任何错误,所以我很难过。 有人有主意吗?
你在循环中第二次调用br.readLine()
。
因此,每次你四处走动时,你最终会读两行。
也非常全面……
try{ InputStream fis=new FileInputStream(targetsFile); BufferedReader br=new BufferedReader(new InputStreamReader(fis)); for (String line = br.readLine(); line != null; line = br.readLine()) { System.out.println(line); } br.close(); } catch(Exception e){ System.err.println("Error: Target File Cannot Be Read"); }
您可以使用如下结构:
while ((line = bufferedReader.readLine()) != null) { System.out.println(line); }
感谢SLaks和jpm的帮助。 这是一个非常简单的错误,我根本没有看到。
正如SLaks指出的那样,每个循环都会调用br.readLine()两次,这使得程序只获得了一半的值。 这是固定代码:
try{ InputStream fis=new FileInputStream(targetsFile); BufferedReader br=new BufferedReader(new InputStreamReader(fis)); String words[]=new String[5]; String line=null; while((line=br.readLine())!=null){ words=line.split(" "); int targetX=Integer.parseInt(words[0]); int targetY=Integer.parseInt(words[1]); int targetW=Integer.parseInt(words[2]); int targetH=Integer.parseInt(words[3]); int targetHits=Integer.parseInt(words[4]); Target a=new Target(targetX, targetY, targetW, targetH, targetHits); targets.add(a); } br.close(); } catch(Exception e){ System.err.println("Error: Target File Cannot Be Read"); }
再次感谢! 你们真棒!
如果你仍然在这个问题上磕磕绊绊。 现在,Java 8看起来更好看:
try { Files.lines(Paths.get(targetsFile)).forEach( s -> { System.out.println(s); // do more stuff with s } ); } catch (IOException exc) { exc.printStackTrace(); }
Concept Solution:br.read() returns particular character's int value so loop continue's until we won't get -1 as int value and Hence up to there it print br.eadline() which returns a line into String form. Way 1: while(br.read()!=-1) { //continues loop until we won't get int value as a -1 System.out.println(br.readLine()); } Way 2: while((line=br.readLine())!=null) { System.out.println(line); } Way 3: for(String line=br.readLine();line!=null;line=br.readLine()) { System.out.println(line); }`` Way 4: It's an advance way to read file using collection and arrays concept How we iterate using for each loop.
在这里查看http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html