我很难弄清楚如何在Android设备上写入和读取文件。该文件将被格式化为XML,我已经构建了解析器和数据结构,可以将XML格式化为对象和对象到XML,但最后一个障碍是从非资源文件中读取XML(我知道数据结构有效,因为我从资源文件中读取它并且还写入非资源文件。我使用工具调试很糟糕(不知道如何打印堆栈跟踪)但我知道问题是我无法读取或写入此文件。我没有使用Java编写文件的经验,这可能就是我在这方面遇到困难的原因。
编写代码:
File scoresFile = new File(getExternalFilesDir(null), "scores.xml");
if (!scoresFile.exists())
{
scoresFile.createNewFile();
}
OutputStream os = new FileOutputStream(scoresFile);
os.write(writer.toString().getBytes());
os.flush();
os.close();
阅读代码:
XmlPullParserFactory xmlFac = XmlPullParserFactory.newInstance();
XmlPullParser qXML = xmlFac.newPullParser();
InputStream is = null;
File scoresFile = new File(c.getExternalFilesDir(null), "scores.xml");
if (!scoresFile.exists())
{
try {
scoresFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
is = new FileInputStream(scoresFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (is != null)
qXML.setInput(is,null);
else
qXML = c.getResources().getXml(R.xml.scores);
UPDATE:读取部分中的最后一个if子句总是计算为false。所以,InputStream是null ...这似乎是我的问题的根源。
答案 0 :(得分:2)
我会看一下这两个链接:Using Internal Storage和Using External Storage
两者都链接到同一页面,只是不同的部分。实际上,这取决于您是否要将此文件保存到设备内存或外部介质(例如SD卡)。