Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting to and Reading from a file in Android
    text
    copied!<p>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. </p> <p>Write code:</p> <pre><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></pre> <p>Read Code:</p> <pre><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); </code></pre> <p>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. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload