[英]Weird Java Null Pointer Exception when writing to XML File
I wrote a code to write all Movies from an Array List in an XML file based on a tutorial from this page here 我写了一个代码,根据来自该网页的教程来写,从一个数组列表的所有电影在一个XML文件在这里
Here is the code that is written in the Repository: 这是存储库中编写的代码:
public void writeMoviesToXML()
{
System.out.println("NULL");
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
Element rootElement = doc.createElement("repo");
doc.appendChild(rootElement);
Element movie = doc.createElement("movie");
rootElement.appendChild(movie);
for (int i=0; i<movieMap.getMovieMap().size(); i++)
{
Attr attr1 = doc.createAttribute("title");
attr1.setValue(movieMap.getMovieMap().get(i).getTitle());
Attr attr2 = doc.createAttribute("rentTimes");
if(movieMap.getMovieMap().get(i).getRentTimes() == null)
System.out.println("NULL");
attr2.setValue(movieMap.getMovieMap().get(i).getRentTimes().toString());
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\Users\\ruspauladrian\\Desktop\\Lab2_4\\movies.xml"));
transformer.transform(source, result);
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
} catch (Exception e)
{
e.printStackTrace();
}
}
And here is the code in the UI where I get the exception: 这是UI中出现异常的代码:
System.out.println("Bye bye");
repository.writeMoviesToXML();
The code is at the end of the program (hence the "Bye Bye"). 该代码位于程序的末尾(因此称为“再见”)。 I want the program to close only after saving the changes.
我希望仅在保存更改后关闭程序。 I have tried debugging it with the "NULL" println in the first code part but it never sees it so I am at a loss why this code is producing a problem without actually entering the function.
我已经尝试在第一个代码部分中使用“ NULL” println对其进行调试,但是它从未看到过,所以我很茫然为什么该代码在没有实际进入函数的情况下会产生问题。
Here are the imports used in the repository if it helps: 如果有帮助,以下是存储库中使用的导入:
import dataStructures.MovieMap;
import dataStructures.PeopleList;
import domain.Movie;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
it seems like repository is null, did you initialize repository first? 似乎存储库为空,您是否首先初始化存储库?
Repository repository = new Repository();
repository.writeMoviesToXML();
you can also make the method writeMoviesToXML static and point to the class. 您还可以将方法writeMoviesToXML设为静态并指向该类。
Repository.writeMoviesToXML();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.