我正在尝试以编程方式将xml文档保存在Sony Android TV的内部存储中。我稍后还需要加入这个文件。它甚至可以做到,我应该如何处理?有什么建议或解决方案吗?
代码:
public class xmlCreateFile {
Boolean finished = false;
String TAG = "xmlCreateFile";
public Boolean xmlCreate(){
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
StreamResult result = new StreamResult(path +"/file.xml");
Log.d(TAG,"Env: " + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS));
//Output to console for testing
StreamResult result2 = new StreamResult(System.out);
// transformer.transform(source, result);
transformer.transform(source, result2);
finished = true;
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
return finished;
}
}
答案 0 :(得分:0)
在设备上存储数据number of ways。您似乎只需要将此信息显示给您的应用,因此您可以使用私人Internal Storage APIs。
这些API使存储和检索文件变得相对容易。这是一个简短的例子。
// Save a file
String FILENAME = "textfile.txt";
String writeString = "hello world!";
FileOutputStream fos = getActivity().openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(writeString.getBytes());
fos.close();
// Read file
FileInputStream fis = getActivity().openFileInput(FILENAME);
StringBuilder builder = new StringBuilder();
int inputChar;
while((inputChar = fis.read()) != -1) {
builder.append((char) inputChar);
}
fis.close();
String readString = builder.toString();