小白今天在写解析XML文件的一个程序时遇到些问题,很不解,希望大牛们给些指导

「已注销」 2017-07-11 07:20:08
今天写一个特别简单的程序发现了一个问题。当使用代码一时会出现文件读写错误。而是用代码二时则程序正常运行。
其中,代码一与代码二如下所示。


代码段一
public  void addPerson(String name,int age,String phone) throws IOException {

File file = new File("/Users/wasim/Workspaces/MyEclipse 2016 CI/connectList/person.xml");
Document doc = null;
OutputStream out=null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputFormat format = OutputFormat.createPrettyPrint();
try {
//---------------------------------------------
doc = XMLUtils.readXML();
if(doc==null)System.out.println("doc is null");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


上变颜色标记代码区域的位置被改变,其他没有什么改动
代码段二
public  void addPerson(String name,int age,String phone) throws IOException {
File file = new File("/Users/wasim/Workspaces/MyEclipse 2016 CI/connectList/person.xml");
try {
//---------------------------------------------
doc = XMLUtils.readXML();
if(doc==null)System.out.println("doc is null");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Document doc = null;
OutputStream out=null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputFormat format = OutputFormat.createPrettyPrint();


绿色标记的函数
public static Document readXML() throws IOException, DocumentException{
Document doc =null;
File XMLfile = new File("/Users/wasim/Workspaces/MyEclipse 2016 CI/connectList/person.xml");
SAXReader reader = new SAXReader();
try{
doc = reader.read(XMLfile);
}
catch(Exception e){
System.out.println("gg");
}
return doc;
}
}

想请问大牛究竟是哪里出了问题。


...全文
150 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
一剑侵心 2017-07-12
  • 打赏
  • 举报
回复
出错时的堆栈信息呢?另外OutputFormat你用的是什么包里的?
我爱娃哈哈 2017-07-11
  • 打赏
  • 举报
回复
堆栈信息呢

51,412

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧