4

I've seen how to write to internal storage using this method..

public void storeSerializedObject(MyObject theObject) {



        FileOutputStream fileOut = null;
        String fileName = theObject.getName();
        try {


            fileOut = context.getApplicationContext().openFileOutput(
                    fileName + ".ser", Context.MODE_PRIVATE);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(theObject);
            out.close();
            fileOut.close();

        } catch (IOException i) {
            i.printStackTrace();
        }

    }

The thing is I want to place theObject in some new specified directory. Then eventually search that directory for all .ser files, and deserialize each object.
So basically, how would you do that?

Also, using the above approach to file storing, is there a way to check that default unnamed location for a list of all filenames within its contents?

Steven Akerfeldt
  • 629
  • 1
  • 7
  • 15

1 Answers1

0

Context has several ways to get internal files and directories, you may want to use Context#getDir().

getDir("serfiles", Context.MODE_PRIVATE) should result in a directory named
/data/data/your.package.name/app_serfiles

To list files in there use File#list() or File#listFiles(). Combine that with a filter in case you want just specific files

private static File[] listSerFiles(Context context, String dirName) {
    File dir = context.getDir(dirName, Context.MODE_PRIVATE);
    return dir.listFiles(SER_FILTER);
}
private static final FileFilter SER_FILTER = new FileFilter() {
    public boolean accept(File file) {
        return file.isFile() && file.getName().endsWith(".ser");
    }
};

And you could open outputstream like

private static FileOutputStream getOutputStreamInDir(Context context, String dirName, String fileName) throws FileNotFoundException {
    File dir = context.getDir(dirName, Context.MODE_PRIVATE);
    File file = new File(dir, fileName);
    return new FileOutputStream(file);
}
zapl
  • 63,179
  • 10
  • 123
  • 154