Java – How do I access another application/data folder through your application?

How do I access another application/data folder through your application?… here is a solution to the problem.

How do I access another application/data folder through your application?

There is an application-generated text file that I want to get and read as a string in my application. How can I do this, any help would be appreciated. Both apps are mine, so I can get permissions.

Thanks!

Solution

This can be done using standard android-storage, which also stores all users’ files:

All you need to do is access the same file and the same path in both applications, for example:

String fileName = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/myFileNameForBothApplications.txt";

myFolderForBothApplications and myFileNameForBothApplications can be replaced with your folder/filename, but this must be the same name in both applications.

Environment.getExternalStorageDirectory() returns the file object to the common, available file directory on the device, which is also visible to the user.
By calling the getPath() method, a string representing this storage path is returned, so you can add your folder/filename later.

So a complete code example is:

String path = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/";
String pathWithFile = path + "myFileNameForBothApplications.txt";

File dir = new File(path);
if(!dir.exists()) {       //If the directory is not created yet
    if(!dir.mkdirs()) {   //try to create the directories to the given path, the method returns false if the directories could not be created
        Make some error-output here
        return;
    }
}
File file = new File(pathWithFile);
try {
    f.createNewFile();
} catch (IOException e) {
    e.printStackTrace();
    File couldn't be created
    return;
}

After that, you can write to or read from the file as provided, for example in this answer

Note that files stored in this way are visible to the user and I can edit/delete by the user.

Also note what the JavaDoc for getExternalStorageDirectory() says:

Returns the primary external storage directory. If the directory has been installed by the user on their computer, removed from the device, or some other problem has occurred, the directory may not be accessible at this time. You can use getExternalStorageState() to determine its current state.

I don’t know if this is the best/safest way to fix the problem, but it should work.

Related Problems and Solutions