BufferedReader没有读取整个在线XML文件

时间:2014-01-09 13:42:45

标签: java xml bufferedreader

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());
    }

}

您好。正如您所看到的那样BufferedReader没有读取整个在线XML文件,我不知道为什么。知道为什么会这样吗? 谢谢。

5 个答案:

答案 0 :(得分:10)

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

每次循环时都会跳过一行......

DO,

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

答案 1 :(得分:4)

考虑使用Scanner,感谢hasNextLine()方法使迭代更直观。

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

答案 2 :(得分:3)

我更喜欢这个成语

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

这很好,因为curLine var只在循环内部需要

答案 3 :(得分:1)

在您的代码中更改此内容。

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

reader1.readLine()将在while循环中读取您的行,并在while循环中读取,这会在不显示整个XML文件时产生问题。

答案 4 :(得分:0)

更改while循环。

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