Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.content.Context;
import android.os.Environment;
import java.io.File;
import java.io.IOException;

public class Main {
    public static File getFilesSubDirectory(Context context, String filesSubDir) {
        File appFilesSubDir = new File(getFilesDirectory(context), filesSubDir);

        if (!appFilesSubDir.exists())
            appFilesSubDir.mkdirs();
        //String filename = String.valueOf(url.hashCode());
        // Another possible solution (thanks to grantland)
        // String filename;
        /*
         * try { filename = URLEncoder.encode(url, "UTF-8"); } catch
         * (UnsupportedEncodingException e) {
         * e.printStackTrace(); }
         */
        return appFilesSubDir;
    }

    /**
     * Returns application files directory. Files directory will be created on SD card
     * <i>("/Android/data/[app_package_name]/files")</i> if card is mounted. Else - Android defines files directory on
     * device's file system.
     * 
     * @param context Application context
     * @return Files {@link File directory}
     */
    public static File getFilesDirectory(Context context) {
        File appFilesDir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            appFilesDir = getExternalFilesDir(context);
        }
        if (appFilesDir == null) {
            appFilesDir = context.getFilesDir();
        }
        return appFilesDir;
    }

    private static File getExternalFilesDir(Context context) {
        File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
        File appFilesDir = new File(new File(dataDir, context.getPackageName()), "files");
        if (!appFilesDir.exists()) {
            if (!appFilesDir.mkdirs()) {
                //L.w("Unable to create external cache directory");
                return null;
            }
            try {
                new File(appFilesDir, ".nomedia").createNewFile();
            } catch (IOException e) {
                //L.i("Can't create \".nomedia\" file in application external cache directory");
                return null;
            }
        }
        return appFilesDir;
    }
}