Reputation: 3984
I have a program which reads contents from a file and prints it on the screen. But program prints every other line i.e., skips every other line. package InputOutput;
import java.io.*;
public class CharacterFileReaderAndFileWriter{
private BufferedReader br = null;
private PrintWriter pw = new PrintWriter(System.out, true);
/* Read from file and print to console */
public void readFromFile() throws IOException{
try{
br = new BufferedReader(new FileReader("E:\\Programming\\Class files\\practice\\src\\InputOutput\\test.txt"));
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
String s = null;
do{
s = br.readLine();
pw.println(s);
}
while((s = br.readLine())!=null);
br.close();
}
/* Main method */
public static void main(String[] args) throws IOException{
CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter();
cfr.readFromFile();
}
}
Upvotes: 1
Views: 2318
Reputation: 11
you are using br.readLine() two times.
String s = null;
do{
s = br.readLine(); //here it read first line
pw.println(s); //here it prints first line
}
while((s = br.readLine())!=null); //here s read second line
//note that it is not printing that line
String s = null;
do{
s = br.readLine(); //this time it read third line
pw.println(s); //now it prints third line
}
while((s = br.readLine())!=null); // this time it reads fourth line
So, this process will go on and your program will print lines one after another
Upvotes: 0
Reputation: 1074
Why are you doing s=br.readline()
twice.. you can have it like this.
String s = null;
while((s = br.readLine())!=null)
{
pw.println(s);
}
readline()
reads a line everytime you call it, and goes to next one. so when you call it twice, obviously you are skipping a line. use this code, and it will work.
Upvotes: 6
Reputation: 42060
Change by:
for(String s; (s = br.readLine()) != null;) {
pw.println(s);
}
Upvotes: 0
Reputation: 2640
You need to modify your do-while loop if you want to go with do-while then kindly code it as follows.
String s = null;
do{
pw.println(s);
}
while((s = br.readLine())!=null);
br.close();
Upvotes: 0
Reputation: 727137
Reverse your do/while
loop to avoid calling readline
twice and discarding every other result:
String s = null;
while((s = br.readLine())!=null) {
pw.println(s);
}
Upvotes: 1
Reputation: 9505
You loop is wrong:
String s = null;
do{
s = br.readLine();
pw.println(s);
}
while((s = br.readLine())!=null);
Should be:
String s = null;
while((s = br.readLine())!=null) {
pw.println(s);
};
Upvotes: 1
Reputation: 5689
remove the first line of your do loop. you are calling readLine() twice.
ie:
String s = null;
while((s = br.readLine())!=null) {
pw.println(s);
}
Upvotes: 0