1

我是java初学者,我正在构建一个android应用程序。

我想要一个包含文本的 xml 文件。每当服务器发送更新时,我都想更改该文件中的某些行(我的意思是更新是通过删除已经写入的文本的某些部分并替换为更新来更改该文件中的某些行)

我对创建、写入或读取文件一无所知。当我搜索时,我发现内部存储最适合我。

但我不知道我是否必须在任何目录中手动创建一个 xml 文件,或者只使用下面的代码自动创建这个文件?

    // If this is the first time run,execute one time code
    // create XML Internal store 

    String FILENAME = "My_XML_file";
    try{
        FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
    } catch (final IOException e) {
        e.printStackTrace();
    }

先感谢您!

4

2 回答 2

0

The code you have will create a file in internal storage but you need a bit more to create and maintain an XML file easily. I suggest you use the Build in Android DOM Parser (Android developers site docs on XML Parse options)

I found this example which explains how to use the dom parser to build a specific (new) XML file from code. In your context where the output stream in created:

StreamResult result = new StreamResult(new File("C:\\file.xml"));

you might want to use the other constructor based on the output stream you created above

StreamResult result = new StreamResult(fos);

In a similar fashion this DOM library allows you to read from an input stream (which you might get from android openFileInput) using DocumentBuilder.parse()

于 2012-10-08T18:47:04.117 回答
0

-首先External Storage permission在 Manifest.xml 文件中给出。

-您可以使用JAXP & JAXB, 甚至CASTOR以更好的方式处理 XML,但仍然DOM内置SAX于 Android 中。

  • 你可以使用这样的东西

    String s = "/sdcard/Myfolder/mytext.txt";

    File f = new File(s);

于 2012-10-08T06:47:23.830 回答