如何从android中的assets文件夹的xml文件创建FileOutputStream?

时间:2015-02-08 12:09:11

标签: android xml fileoutputstream

我正在尝试将xml节点添加到assets文件夹中的现有xml文件favorites.xml。

下面是代码。在行中创建FileOutputStream时抛出FileNotFoundException

FileOutputStream fos = new FileOutputStream(myContext.getAssets().openFd("favorites.xml").getFileDescriptor());

请帮我解决。提前谢谢。

代码:

import android.content.Context;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


public class XMLWriter{

private Context myContext;
public XMLWriter(Context context)
{
    myContext = context;
}

public void AddFavorites(int id)
{
    try
    {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        Document document = documentBuilder.parse(myContext.getAssets().open("favorites.xml"));
        Node node = document.getElementsByTagName("favorites").item(0);

        Element favorite = document.createElement("favorite");
        Element idElement = document.createElement("id");
        idElement.appendChild(document.createTextNode(Integer.toString(id)));
        favorite.appendChild(idElement);
        node.appendChild(favorite);

        DOMSource source = new DOMSource(document);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        FileOutputStream fos = new FileOutputStream(myContext.getAssets().openFd("favorites.xml").getFileDescriptor());
        StreamResult result = new StreamResult(fos);
        transformer.transform(source, result);

    } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) {
        e.printStackTrace();
    }
}

}

2 个答案:

答案 0 :(得分:0)

您无法更改资源文件夹中的文件。它们是只读的。

答案 1 :(得分:0)