Android重写为文件会创建新的

时间:2017-08-10 10:59:53

标签: java android xml file

我有一段代码可以创建一个xml文件:

File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "android/data/com.travip");
directory.mkdirs();

FileOutputStream fos = new FileOutputStream(file);

XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("UTF-8", true);
xmlSerializer.startTag(null, "trip");
xmlSerializer.attribute(null, "name", name);
xmlSerializer.attribute(null, "description", description);
xmlSerializer.attribute(null, "startdate", startdate);
xmlSerializer.attribute(null, "enddate", enddate);
xmlSerializer.endTag(null, "trip");
xmlSerializer.endDocument();
xmlSerializer.flush();
String dataWrite = writer.toString();
fos.write(dataWrite.getBytes());
fos.close();

SharedPreferences sharedpreferences;
SharedPreferences.Editor prefseditor;
sharedpreferences = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
prefseditor = sharedpreferences.edit();
prefseditor.putString("activeTrip", name);
prefseditor.apply();

这给我一个“trip.trp名称”形式的文件。创建此文件后,我想编辑它(添加一些节点)。这是代码:

File file = new File(Environment.getExternalStorageDirectory() + "/" + "android/data/com.travip/" + activeTrip + ".trp");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
Element root = document.getDocumentElement();
Element activities = document.createElement("activities");
if (root.getElementsByTagName("activities").getLength() == 0) {
    root.appendChild(activities);
    NodeList activitiesNodes = document.getElementsByTagName("activities");
    activities = (Element) activitiesNodes.item(0);
} else {
    NodeList activitiesNodes = document.getElementsByTagName("activities");
    activities = (Element) activitiesNodes.item(0);
}

Element activity = document.createElement("activity");

activity.setAttribute("name", name);
activity.setAttribute("latLng", latLng);
activity.setAttribute("date", date);
activity.setAttribute("time", time);

activities.appendChild(activity);
DOMSource source = new DOMSource(document);

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(file);
transformer.transform(source, result);

但是如果文件的文件名(已编辑)包含空格,则该空格将替换为%20。所以现在我有两个文件,一个没有更改的“trip.trp的名称”和一个带有更改的“name%20of%20the%20trip.trp”。如何将这些更改写入同一文件?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我发现了这个问题: 别问我原因,但我不得不更换

StreamResult result = new StreamResult(file);

StreamResult result = new StreamResult(new FileOutputStream(file));

我发出了声音here