
May 1st, 2012, 10:23 AM
|
 |
Contributing User
|
|
|
|
|
Check, create and read from file in internal storage
Hi,
I am trying to get my android app to do the following:
1. Check to see if a file exists within the application folder on internal storage (NOT SD! NOT EXTERNAL!).
2. If the file does not exist, create it by copying the file from resources folder into the application folder.
3. Read the new file.
The following code will check and create the file if necessary. FileData is just a basic structure for holding the name and byte array data.
Code:
final static String VERSION_FILE = "content.xml";
File versionFile = new File(VERSION_FILE);
if (!versionFile.exists()) {
new CreateFile().execute(new FileData(VERSION_FILE, getResources().getXml(R.xml.content).toString().getBytes()));
}
private class CreateFile extends AsyncTask<FileData, Integer, Boolean> {
@Override
protected Boolean doInBackground(FileData... fd) {
FileOutputStream fos = null;
try {
fos = openFileOutput(fd[0].getFilename(), Context.MODE_PRIVATE);
fos.write(fd[0].getData());
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}
I then create an input stream for an XML parser to handle by doing the following and passing it to an input source:
Code:
InputStream is;
File f = new File(VERSION_FILE);
is = new FileInputStream(f);
However once this reaches the parser an exception is thrown to say the file does not exist.
I cannot see what I am doing wrong since the documentation on the android site and pretty much every google search I have made suggests that the file should be created or overwritten by my first few lines of code.
|