写入和Android中文件读取 [英] Writing to and Reading from a file in Android
问题描述
我有一个很难搞清楚如何写入和文件在Android设备上阅读。该文件将被格式化为XML,我已经有解析器和数据结构,建立了可以在XML格式化成对象和对象转换为XML,但最后一关是阅读从非资源文件的XML(我知道数据结构的工作,因为从资源文件中读取),并写入到一个非资源文件时,我它的工作原理。我在使用工具来调试可怕的(不知道如何打印堆栈跟踪),但我知道一个事实,问题是我无法从读取或写入该文件。我没有经验写在Java文件这可能是为什么我有一个粗略的时间与此有关。
I am having a hard time figuring out how to write to and read from files on an Android device. The file will be formatted as XML and I already have parsers and data structures built that can format the XML into objects and objects into XML, but the last hurdle is reading the XML from a non-resource file (I know the data structures work because I it works when reading from a resource file) and also writing to a non-resource file. I am terrible at using tools to debug (not sure how to print a stack trace) but I know for a fact the problem is that I cannot read from or write to this files. I have no experience writing to files in Java which may be why I am having a rough time with this.
写code:
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();
阅读code:
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);
更新:最后,如果在读出部分条款的结果总是为false。因此,InputStream为null ......这似乎是我的问题的根源。
UPDATE: The last if clause in the read section always evaluates to false. So, the InputStream is null... that appears to be the root of my problem.
推荐答案
I would take a look at these two links: Using Internal Storage and Using External Storage
这两个链接到同一个页面,只是不同的部分。真的,这取决于你是否希望保存此文件到设备内存,或外部介质(如SD卡)。
Both link to the same page, just different portions. Really, it depends on whether or not you want to save this file to the devices memory, or to an external medium (such as an SDcard).
- 内部 - 沙盒,这样只有您的应用程序可以访问它
- 外部 - 任何人都可以访问它
这篇关于写入和Android中文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!