Java tutorial
//package com.java2s; //License from project: Apache License import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import android.annotation.TargetApi; import android.os.Build; import android.support.annotation.NonNull; import android.util.Log; public class Main { public static Context applicationContext; /** * Determine if a file is on external sd card. (Kitkat or higher.) * * @param file The file. * @return true if on external sd card. */ @TargetApi(Build.VERSION_CODES.KITKAT) public static boolean isOnExtSdCard(@NonNull final File file) { return getExtSdCardFolder(file) != null; } /** * Determine the main folder of the external SD card containing the given file. * * @param file the file. * @return The main folder of the external SD card containing this file, if the file is on an SD card. Otherwise, * null is returned. */ @TargetApi(Build.VERSION_CODES.KITKAT) public static String getExtSdCardFolder(@NonNull final File file) { String[] extSdPaths = getExtSdCardPaths(); try { for (String extSdPath : extSdPaths) { if (file.getCanonicalPath().startsWith(extSdPath)) { return extSdPath; } } } catch (IOException e) { return null; } return null; } /** * Get a list of external SD card paths. (Kitkat or higher.) * * @return A list of external SD card paths. */ @TargetApi(Build.VERSION_CODES.KITKAT) private static String[] getExtSdCardPaths() { List<String> paths = new ArrayList<>(); for (File file : applicationContext.getExternalFilesDirs("external")) { if (file != null && !file.equals(applicationContext.getExternalFilesDir("external"))) { int index = file.getAbsolutePath().lastIndexOf("/Android/data"); if (index < 0) { Log.w("Uri", "Unexpected external file dir: " + file.getAbsolutePath()); } else { String path = file.getAbsolutePath().substring(0, index); try { path = new File(path).getCanonicalPath(); } catch (IOException e) { // Keep non-canonical path. } paths.add(path); } } } return paths.toArray(new String[paths.size()]); } }