Skip to content Skip to sidebar Skip to footer

Save File In The Internal Storage Of Android Device

I'm trying to make an application that save a temporary file on the sd card. if the user don't have a sd card I want the application save the file in internal storage sory for my e

Solution 1:

This is what I use for caching on either the SD card, or the internal storage, but be careful. You have to regularly clear your cache, especially on the internal storage.

private static boolean sIsDiskCacheAvailable = false;
private static File sRootDir = null;

public static void initializeCacheDir(Context context){
    Context appContext = context.getApplicationContext();

    File rootDir = null;

    if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
        // SD card is mounted, use it for the cache
        rootDir = appContext.getExternalCacheDir();
    } else {
        // SD card is unavailable, fall back to internal cache
        rootDir = appContext.getCacheDir();

        if(rootDir == null){
            sIsDiskCacheAvailable = false;
            return;
        }
    }

    sRootDir = rootDir;

    // If the app doesn't yet have a cache dir, create it
    if(sRootDir.mkdirs()){
        // Create the '.nomedia' file, to prevent the mediastore from scanning your temp files
        File nomedia = new File(sRootDir.getAbsolutePath(), ".nomedia");
        try{
            nomedia.createNewFile();
        } catch(IOException e){
            Log.e(ImageCache.class.getSimpleName(), "Failed creating .nomedia file!", e);
        }
    }

    sIsDiskCacheAvailable = sRootDir.exists();

    if(!sIsDiskCacheAvailable){
        Log.w(ImageCache.class.getSimpleName(), "Failed creating disk cache directory " + sRootDir.getAbsolutePath());
    } else {
        Log.d(ImageCache.class.getSimpleName(), "Caching enabled in: " + sRootDir.getAbsolutePath());

        // The cache dir is created, you can use it to store files
    }
}

Solution 2:

You can use Context's getExternalCacheDir() method to get a File reference where you can store files on an SD card. Of course, you'll have to do the usual checks to make sure the external storage is mounted and writable, as usual, but this is probably the best place to store that type of temporary file. One thing you might want to do is just set a maximum amount of space that you can use in the cache directory, and then, any time you need to write a new temporary file, if that file exceeds the maximum space, then start deleting the temp files, starting with the oldest, until there is sufficient space. Alternatively, maybe something like this would work:

 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File externalRoot = Environment.getExternalStorageDirectory();
File tempDir = new File(externalRoot, ".myAppTemp");
 }

Prepending the "." should make the folder hidden, I'm fairly sure.


Post a Comment for "Save File In The Internal Storage Of Android Device"