0

我有一个 android 应用程序,我正在尝试更改节点值。

下面我可以从 assets 文件夹中获取 xml 文件并获取我想要的特定节点。

InputStream in_s = getApplicationContext().getAssets().open("platform.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = (Document) docBuilder.parse(in_s);

Node path = doc.getElementsByTagName("path").item(0);
path.setNodeValue(txtPath.getText().toString());

但是当谈到转型时,我卡住了。

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer trans = transFactory.newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult("platform.xml");
//there should be something to write to xml file in assets.. I just cant figure it out..
trans.transform(source, result);
4

2 回答 2

0

您不能在资产文件夹中写入/更新文件。您需要将 xml 文件从 assets 复制到 sdcard,然后对其进行修改。

将 xml 复制到 SD 卡:

String destFile = Environment.getExternalStorageDirectory().toString();
try {

        File f2 = new File(destFile);
        InputStream in = getAssets().open("file.xml");
        OutputStream out = new FileOutputStream(f2);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        System.out.println("File copied.");
    } catch (FileNotFoundException ex) {
        System.out
                .println(ex.getMessage() + " in the specified directory.");
        System.exit(0);
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

清单中的权限:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
于 2014-02-03T07:57:32.910 回答
0

Android 资源都是只读的。您不能动态更改或修改它。您只能读取资源,不能更新,也不能写入。

于 2014-02-03T08:00:28.217 回答