user1843145
user1843145

Reputation: 35

readLine() null return

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.

Upvotes: 2

Views: 12712

Answers (3)

yakshaver
yakshaver

Reputation: 2492

You're throwing away every odd line:

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

If r.txt only contains one line, you will get the string "null" in the StringBuffer, because the first line of StringBuffer.append does this:

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.

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

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

Upvotes: 1

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

your code

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

change with it

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

 }

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53525

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.

Upvotes: 2

Related Questions