在android中创建XML文件

时间:2016-12-06 02:55:37

标签: android xml

所以我在MainActivity中调用了这个方法..

public void CreateXMLFile() throws ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("user");
    doc.appendChild(rootElement);

    Element name = doc.createElement("name");
    rootElement.appendChild(name);

    Element displayInstructions = doc.createElement("displayInstructions");
    rootElement.appendChild(displayInstructions);

    Element scores = doc.createElement("scores");
    rootElement.appendChild(scores);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(context.getFilesDir(), "info.xml"));
    transformer.transform(source, result);
}

问题是..我实际上并不知道它是否正在创建。有没有办法检查?

1 个答案:

答案 0 :(得分:1)

如果要检查文件是否已创建,可以执行以下操作

File file = new File(this.getFilesDir(), "info.xml");
if (file.exists()) {
    //Do something
    Log.d("","file is available");
} else {
    // Do something else.
    Log.d("","file is not available");
}

上面的代码将检查文件是否存在。

请注意,这是基于我对您提供的有关问题的有限信息的理解。