Writing to and Reading from a file in Android

我的梦境 提交于 2019-12-11 18:17:28

问题


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.

Write 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();

Read 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);

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.


回答1:


I would take a look at these two links: Using Internal Storage and Using External Storage

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).

  1. Internal - Sandboxed, so that only your app can access it.
  2. External - Anyone can access it.


来源:https://stackoverflow.com/questions/6847572/writing-to-and-reading-from-a-file-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!