java readLine() 返回 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13889652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:20:21  来源:igfitidea点击:

readLine() null return

java

提问by user1843145

I have the following code:

我有以下代码:

public static void main(String[] args) throws Exception {
    String s = "";
    StringBuilder sb = new StringBuilder();
    File file = new File("C:\New\r.txt");

    BufferedReader in = new BufferedReader(new FileReader(file));
    while(in.readLine() != null) {      
        sb.append(in.readLine());
    }

    System.out.println(sb);
    s = sb.toString();
    byte[] b = s.getBytes();

   for(int i = 0; i < b.length; i++) {
       if(b[i] == 1){ b[i]=0; }
       if(b[i] == 0){ b[i]=1; }
   }

   FileOutputStream fos = new FileOutputStream(file);
   DataOutputStream dos = new DataOutputStream(fos);
   dos.write(b);
   in.close();
   fos.close();
   dos.close();
}

I get a return of null when I run this program. Maybe I must elevate the program? Help would be appreciated.

当我运行这个程序时,我得到了 null 的返回。也许我必须提升程序?帮助将不胜感激。

采纳答案by alfasin

Change:

改变:

 while(in.readLine()!=null)

to:

到:

 while((s = in.readLine())!=null)

and then:

接着:

sb.append(s);

When you call in your code to in.readLine()twice - you're reading two lines but printing only the second in each iteration.

当您将代码调用in.readLine()两次时 - 您正在阅读两行,但在每次迭代中仅打印第二行。

回答by yakshaver

You're throwing away every odd line:

你扔掉了每一个奇数行:

while(in.readLine()!=null)
{      
   sb.append(in.readLine());
}

If r.txtonly contains one line, you will get the string "null" in the StringBuffer, because the first line of StringBuffer.appenddoes this:

如果r.txt只包含一行,您将在 中得到字符串“null” StringBuffer,因为 的第一行是StringBuffer.append这样做的:

public AbstractStringBuilder append(String str) {
  if (str == null) str = "null";
  ....
}

If there are two lines, you will get the first line with "null" at the end of the line.

如果有两行,您将得到第一行,该行末尾带有“null”。

The following will append all lines from the file to the StringBuffer:

以下内容会将文件中的所有行附加到StringBuffer

String line = null;
while((line = in.readLine()) != null)
{      
   sb.append(line);
}

回答by Mohammod Hossain

your code

你的代码

while(in.readLine() != null) {      
        sb.append(in.readLine());
    }

change with it

随之改变

  while ((s = in.readLine()) != null)
 {               
    sb.append(s);

 }