Martin1993-03
Martin1993-03

Reputation: 127

BufferedReader not reading whole online XML file

public static void main(String[] args) throws MalformedURLException, IOException 
{
    // TODO code application logic here
    URL link1 = new URL("xmlFileHere");
    InputStream xml = link1.openStream();
    InputStreamReader reader = new InputStreamReader(xml);
    BufferedReader reader1 = new BufferedReader(reader);
    while(reader1.readLine()!= null)
    {
        System.out.println(reader1.readLine());
    }

}

Hello. As you can see my BufferedReader is not reading the whole online XML file, I don't know why. Any idea why this happens?
Thank you.

Upvotes: 4

Views: 3965

Answers (5)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

I prefer this idiom

for (String curLine; (curLine=reader1.readLine()) != null;) {
    System.out.println(curLine);
}

it's good because curLine var is needed only inside loop

Upvotes: 3

Pshemo
Pshemo

Reputation: 124275

Consider using Scanner which thanks to hasNextLine() method makes iterating more intuitive.

Scanner scanner = new Scanner(reader1);
while (scanner.hasNextLine() ) {//check if next line exists
    System.out.println(scanner.nextLine());//use this next line
}
scanner.close();

Upvotes: 4

Daniel Lin
Daniel Lin

Reputation: 4023

Change the while loop.

    String line;
    while( (line=reader1.readLine() ) != null)
    {
        System.out.println(line);
    }

Upvotes: 0

Yagnesh Agola
Yagnesh Agola

Reputation: 4659

Change this in your code.

String curLine = "";
while((curLine=reader1.readLine())!= null)
{
    System.out.println(curLine);
}

reader1.readLine() will read your line in while loop and again inside while loop which create problem in not displaying whole XML file.

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

while(reader1.readLine()!= null)   // reading here
{
System.out.println(reader1.readLine());  // and here
}

You are skipping a line each time you loop...

Do,

String line=null;
while((line=reader1.readLine())!= null)   // reading here
{
System.out.println(line);  // and displaying here
}

Upvotes: 10

Related Questions