java中的打开文件无法正常工作

时间:2013-09-02 17:12:52

标签: java xml file

我的代码:

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文件,我将不胜感激?前两行在哪里,以及为什么插入的最后一个字符串为空?

1 个答案:

答案 0 :(得分:1)

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

试试这个:

String data = "";
String temp = "";
while ((temp = br.readLine()) != null)
{
   data += temp;
}