我有这段代码可以生成 XML 文件并保存到外部目录。
try //database structure
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//test report elements, does not reflect the real database in the future
//mandatory/ username, location, caption, media, time(Actually, it's best if the server determines recieve time)
//optional/
//reportdata elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("reportdata");
doc.appendChild(rootElement);
//username elements
Element username = doc.createElement("username");
username.appendChild(doc.createTextNode("testusername"));
rootElement.appendChild(username);
//Location ELEMENTS
//latitude elements
Element lat = doc.createElement("latitude");
lat.appendChild(doc.createTextNode(String.valueOf(latitude)));
rootElement.appendChild(lat);
//longitude
Element longi = doc.createElement("longitude");
longi.appendChild(doc.createTextNode(String.valueOf(longitude)));
rootElement.appendChild(longi);
//caption text elements
Element capt = doc.createElement("caption");
capt.appendChild(doc.createTextNode(captionText.getText().toString()));
rootElement.appendChild(capt);
//tag elements
String[] tagArr = new String[selectItems.size()];
tagArr = selectItems.toArray(tagArr);
Element tags = doc.createElement("tags");
rootElement.appendChild(tags);
int o = selectItems.size();
for(String s: tagArr) {
Element tagname = doc.createElement("tagname");
tagname.appendChild(doc.createTextNode(s));
tags.appendChild(tagname);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
//StreamResult result = new StreamResult(System.out);
StreamResult result = new StreamResult(new File(android.os.Environment.getRootDirectory(), "upload_data.xml"));
transformer.transform(source, result);
Log.d("MESSAGE", result.toString());
创建 XML 文件后,引发此异常
D/XML TransformerException﹕ java.io.FileNotFoundException: /system/upload_data.xml: open failed: EROFS (Read-only file system)
有什么办法可以解决这个问题吗?
最佳答案
... saves to an external directory
这不太对。您正在尝试将其保存在 root 中始终只读的系统分区。
来自 Environment.getRootDirectory() 的 javadoc :
Return root of the "system" partition holding the core Android OS. Always present and mounted read-only.
解决方案:将您的文件保存在其他地方:
StreamResult result = new StreamResult(new File(android.os.Environment.getExternalStorageDirectory(), "upload_data.xml"));
请注意:
- 您必须请求写入外部存储的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- 外部存储并非总是可用。当您尝试在分区上写入时,该分区可能尚未安装。 (小心一点)
关于java.io.FileNotFoundException : open failed: EROFS (Read-only file system) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27103877/