Writing to an existing resource XML file in Android

那年仲夏 提交于 2019-12-25 03:28:12

问题


I am trying to write to an existing XML file in the /res/xml directory on an Android device. Two questions:

1) Are these files able to be overwritten? 2) If so, how can I obtain a handle to that file?

I am trying this to no avail:

    FileOutputStream fos;

    try {
        fos = openFileOutput("/res/xml/scores.xml", Context.MODE_PRIVATE);
        fos.write(writer.toString().getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

UPDATE

Trying to read from the file using:

....
        PriorityQueue<Score> scores = new PriorityQueue<Score>();
    XmlPullParserFactory xmlFac = XmlPullParserFactory.newInstance();
    XmlPullParser qXML = xmlFac.newPullParser();
    File scoresFile = new File(c.getExternalFilesDir(null), "scores.xml");
    InputStream is = new FileInputStream(scoresFile);
    qXML.setInput(is,null);
....

Trying to write to the file using:

....
    File scoresFile = new File(getExternalFilesDir(null), "scores.xml");
    OutputStream os = new FileOutputStream(scoresFile);

    os.write(writer.toString().getBytes());
    os.flush();
    os.close();
....

回答1:


You need to use the external storage on the device. You can't and shouldn't be writing to the resources. Instead, copy the resource to the external storage, and then modify it there.

EDIT: You can also use your application's internal data folder to save files to, but again, you will want to copy your resource there if you want to modify it. This will allow the files to remain internal to your application.



来源:https://stackoverflow.com/questions/6835339/writing-to-an-existing-resource-xml-file-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!