Writing an object to internal storage in android (inside a new directory)

I saw how to write to internal memory 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 fact is that I want to put the object in some new specified directory. Then eventually find this directory for all .ser files and deserialize each object.
So basically, how would you do this?

Also, using the above approach to file storage, is there a way to check, not by default, the default name for a list of all file names in its contents?

+4
source share
1 answer

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

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

To view a list of files, use File#list() or File#listFiles() . Combine this with a filter if you want only certain 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 can open the output stream, for example

 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); } 
0
source

All Articles