创建xml文件并将其保存在内部存储Android中 [英] Create xml file and save it in internal storage android

查看:148
本文介绍了创建xml文件并将其保存在内部存储Android中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在android内部存储中检查new.xml是否存在(它将由我创建),那么它应该为我返回一个句柄,并且我很容易能够向其添加新数据.不存在,请创建一个新文件并向其中添加数据.

I want to check in the android internal storage if new.xml exists(which will be created by me) then it should return me a handle for it and i may be easily able to append new data to it.If it doesn't exists create a new one and add data to it.

我的xml文件结构将很简单.

My xml file structure will be simple like this.

<root>
    <record>a</record>
    <record>b</record>
    <record>c</record>
</root>

如果文件存在,我只会向其中添加一条新记录.但是如果没有,我将创建一个新文件并向其中添加第一条记录.

If the file is there I will only add a new record to it.But if doesn't than I will create a new file and add the first record to it.

以及如何在arraylist中读取此数据.预先提供示例代码非常感谢.

And How I will be able to read this data in an arraylist. An example with code would be great thanks in advance.

推荐答案

这很简单.这将为您提供帮助:

It's rather simple. This will help you:

String filename = "file.txt";

FileOutputStream fos;
fos = openFileOutput(filename,Context.MODE_APPEND);

XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(fos, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

serializer.startTag(null, "root");

for(int j = 0; j < 3; j++)
{
    serializer.startTag(null, "record");
    serializer.text(data);
    serializer.endTag(null, "record");
}

serializer.endDocument();
serializer.flush();

fos.close();

要使用DOM解析器读回数据,请执行以下操作:

To read back data using DOM parser:

FileInputStream fis = null;
InputStreamReader isr = null;

fis = context.openFileInput(filename);
isr = new InputStreamReader(fis);

char[] inputBuffer = new char[fis.available()];
isr.read(inputBuffer);

data = new String(inputBuffer);

isr.close();
fis.close();

/*
* Converting the String data to XML format so
* that the DOM parser understands it as an XML input.
*/

InputStream is = new ByteArrayInputStream(data.getBytes("UTF-8"));
ArrayList<XmlData> xmlDataList = new ArrayList<XmlData>();

XmlData xmlDataObj;
DocumentBuilderFactory dbf;
DocumentBuilder db;
NodeList items = null;
Document dom;

dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
dom = db.parse(is);

// Normalize the document
dom.getDocumentElement().normalize();

items = dom.getElementsByTagName("record");
ArrayList<String> arr = new ArrayList<String>();

for (int i = 0; i < items.getLength(); i++)
{
    Node item = items.item(i);
    arr.add(item.getNodeValue());
}

这篇关于创建xml文件并将其保存在内部存储Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆