Java tutorial
//package com.java2s; /******************************************************************************* * Copyright 2011-2014 Sergey Tarasevich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ import android.content.Context; import android.content.pm.PackageManager; import android.os.Environment; import java.io.File; import static android.os.Environment.MEDIA_MOUNTED; public class Main { private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE"; /** * Returns specified application cache directory. Cache directory will be created on SD card by defined path if card * is mounted and app has appropriate permission. Else - Android defines cache directory on device's file system. * * @param context Application context * @param cacheDir Cache directory path (e.g.: "AppCacheDir", "AppDir/cache/images") * @return Cache {@link File directory} */ public static File getOwnCacheDirectory(Context context, String cacheDir) { File appCacheDir = null; if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) { appCacheDir = new File(Environment.getExternalStorageDirectory(), cacheDir); } if (appCacheDir == null || (!appCacheDir.exists() && !appCacheDir.mkdirs())) { appCacheDir = context.getCacheDir(); } return appCacheDir; } /** * Returns specified application cache directory. Cache directory will be created on SD card by defined path if card * is mounted and app has appropriate permission. Else - Android defines cache directory on device's file system. * * @param context Application context * @param cacheDir Cache directory path (e.g.: "AppCacheDir", "AppDir/cache/images") * @return Cache {@link File directory} */ public static File getOwnCacheDirectory(Context context, String cacheDir, boolean preferExternal) { File appCacheDir = null; if (preferExternal && MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) { appCacheDir = new File(Environment.getExternalStorageDirectory(), cacheDir); } if (appCacheDir == null || (!appCacheDir.exists() && !appCacheDir.mkdirs())) { appCacheDir = context.getCacheDir(); } return appCacheDir; } private static boolean hasExternalStoragePermission(Context context) { int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION); return perm == PackageManager.PERMISSION_GRANTED; } }