在java isn'中打开文件;t工作不正常
我的代码:在java isn'中打开文件;t工作不正常,java,xml,file,Java,Xml,File,我的代码: JFileChooser opChooser=new JFileChooser(); FileNameExtensionFilter filter=new FileNameExtensionFilter("XML File", "xml"); opChooser.setFileFilter(filter); int returnVal=opChooser.showOpenDialog(null);
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文件,我将不胜感激?前两行在哪里,以及插入的最后一个字符串为何为空?您在while条件下调用
br.readLine()
,但未将其设置为值
试试这个:
String data = "";
String temp = "";
while ((temp = br.readLine()) != null)
{
data += temp;
}
对于
数据
应使用StringBuilder
,而不是字符串
。