Reading a cache file previously written by the same app

Richard picture Richard · Feb 8, 2011 · Viewed 14.8k times · Source

I'm writing to a file using the code below:

File file = new File(getCacheDir(), "cachefile");
FileOutputStream fos = new FileOutputStream(file);
StringBuilder cachetext = new StringBuilder();
Iterator bri = brands.iterator();
Iterator bli = brand_id.iterator();
while(bli.hasNext()) {
    cachetext.append(bli.next() + "|" + bri.next() + System.getProperty("line.separator"));
}
fos.write(cachetext.toString().getBytes());
fos.close();

This works fine - no errors and the file ends up containing what I expect it to contain. When I go to read it via openFileInput(), however, I get an exception telling me that path separators are not allowed

FileInputStream fis = openFileInput(getCacheDir() + "/cachefile");

Fair enough, that contains a slash, but how else can I specify the path of the file I want to open? There must be a way to do this, of course, but I can't find answers via Google ('read', 'cache' and 'file' not being the most niche of terms ...) so I thought I'd try the human touch. Thanks in advance!

Answer

James Dunham picture James Dunham · May 12, 2011

you do it pretty much the same way you created the output file:

FileInputStream fis = new FileInputStream(new File(getCacheDir(), "cachefile"));