我正在尝试使用“内部存储”的方法来保留我的数据。在下面的代码中,我试图将 xml 写入存储。这是正确的方法吗?我正在尝试使用 fileInputStream 打开此文件,但我看到的该类的唯一读取函数是 .read() ,它显然一次读取一个字节的数据。这对于读取 xml 文件似乎很不方便。我应该如何最好地读/写我的数据?
@Override
protected void onDestroy() {
super.onDestroy();
try {
FileOutputStream fos=openFileOutput(LOCALSTORAGEFILE,Context.MODE_PRIVATE);
XmlCreator create=new XmlCreator();
fos.write(create.subjectListToXml(subjectMasterList).getBytes());
fos.close();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
public class XmlCreator {
XmlSerializer serializer=Xml.newSerializer();
StringWriter writer=new StringWriter();
public String subjectListToXml(ArrayList<Subject> masterList){
try{
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
serializer.startTag("", "subjects");
serializer.attribute(null, null, null);
for(Subject subject:masterList){
serializer.endTag("","subject");
for(Cards card:subject.getCards()){
serializer.startTag("","card");
serializer.startTag("","word");
serializer.text(card.getCardFront());
serializer.endTag("","word");
serializer.endTag("", "card");
}
serializer.endTag("", "subject");
}
serializer.endTag("","subjects");
serializer.endDocument();
}catch(Exception e){
e.printStackTrace();
}
return writer.toString();
}
}