0

我的代码:

JFileChooser opChooser=new JFileChooser();
            FileNameExtensionFilter filter=new FileNameExtensionFilter("XML File", "xml");
            opChooser.setFileFilter(filter);
            int returnVal=opChooser.showOpenDialog(null);
            File chosenFile=opChooser.getSelectedFile();

            try
            {
                if (returnVal==JFileChooser.APPROVE_OPTION)
                {
                    BufferedReader br=new BufferedReader(new FileReader(chosenFile));
                    currentDirectory="";
                    textPane.setText("");
                    textPaneError.setText("");
                    currentDirectory=chosenFile.getAbsolutePath();

                    String data = "";
                    while ((br.readLine())!=null)
                    {
                        data += br.readLine();
                    }
                    doc.insertString(0, data, null);
                    br.close();
                }
            }
            catch (IOException | BadLocationException ex)
            {
                JOptionPane.showMessageDialog(null, "ERROR!!!");
            }
        }

我想在我的应用程序中打开的 xml 文件:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

结果:

<from>Jani</from><body>Don't forget me this weekend!</body>null

如果有人能解释一下为什么结果不像 xml 文件,我将不胜感激?前两行在哪里,为什么最后插入的字符串为空?

4

1 回答 1

1

您正在调用br.readLine()while 条件而不将其设置为值

尝试这个:

String data = "";
String temp = "";
while ((temp = br.readLine()) != null)
{
   data += temp;
}
于 2013-09-02T17:18:54.107 回答