1

我在资产文件夹中有一个“config.xml”文件。我使用以下代码从中读取:

public static String readAppConfigKey(Context context, String section,
        String key) {
    String value = "";
    AssetManager assetManager = context.getAssets();

    InputStream istr;
    try {
        istr = assetManager.open("config.xml");
        XmlPullParserFactory factory;
        factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xmlParser = factory.newPullParser();
        xmlParser.setInput(istr, "UTF-8");

        String strPrevElement = "";
        String strElement = "";
        String strKey = "";

        xmlParser.next();
        int eventType = xmlParser.getEventType();
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            if (eventType == XmlResourceParser.START_TAG) {
                if (xmlParser.getName().compareTo(strElement) != 0) {
                    // after any change
                    strPrevElement = strElement;
                    strElement = xmlParser.getName();
                }
                strKey = xmlParser.getAttributeValue(null, "key");
                if (strPrevElement.compareTo(section) == 0
                        && strKey != null && strKey.compareTo(key) == 0) {
                    value = xmlParser.getAttributeValue(null, "value");
                    return value;
                }
            }
            eventType = xmlParser.next();
        }
    } catch (XmlPullParserException e) {

    } catch (IOException e) {

    }
    return value;
}

如何使用 XmlPullParser 在其中写入?

谢谢,

4

2 回答 2

3

我不相信您可以写入资产文件夹中的文件。我认为您必须将其复制到 sdcard 并在那里对其进行读写。

此外,XmlPullParser 只读取 XML,它不写入。查看本教程了解如何修改 XML:

如何在 Java 中修改 XML 文件

于 2011-07-10T12:19:03.343 回答
0

如果你有 InputStream 你有文件的字节,如果你有文件的字节将它们写入磁盘(:

        //1. Convert the inputStream to Byte Array
        InputStream inputStream = . . .

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[Integer.MAX_VALUE]; //need to make sure here that the inputstream is less then 2g (Integer.MAX_VALUE), in case its bigger file we will need to read and write in parts
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();

        byte[] xmlFileBytes = buffer.toByteArray();

        //2.  write the bytes to file
        String filePath = "file.xml";
        File file = new File(filePath);
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(xmlFileBytes);
        outputStream.close();
于 2020-12-07T11:38:45.217 回答