Oceanuz が提供するパスに基づいて、(大文字と小文字を区別せずに) 外部ストレージ パスを検索し、それを文字列として返すメソッドを作成しました。
注:メソッド内でStreamSupportライブラリを使用したので、それを機能させるには、jar ファイルをダウンロードしてプロジェクトの libs フォルダーに追加する必要があります。それだけです。
public static String getExternalSdPath(Context context) {
List<String> listOfFoldersToSearch = Arrays.asList("/storage/", "/mnt/", "/removable/", "/data/");
List<String> listOf2DepthFolders = Arrays.asList("sdcard0", "media_rw", "removable");
List<String> listOfExtFolders = Arrays.asList("sdcard1", "extsdcard", "external_sd", "microsd", "emmc", "ext_sd", "sdext",
"sdext1", "sdext2", "sdext3", "sdext4");
final String[] thePath = {""};
Optional<File> optional = StreamSupport.stream(listOfFoldersToSearch)
.filter(s -> {
File folder = new File(s);
return folder.exists() && folder.isDirectory();
}) //I got the ones that exist and are directories
.flatMap(s -> {
try {
List<File> files = Arrays.asList(new File(s).listFiles());
return StreamSupport.stream(files);
} catch (NullPointerException e) {
return StreamSupport.stream(Collections.emptyList());
}
}) //I got all sub-dirs of the main folders
.flatMap(file1 -> {
if (listOf2DepthFolders.contains(file1.getName().toLowerCase())) {
try {
List<File> files = Arrays.asList(file1.listFiles());
return StreamSupport.stream(files);
} catch (NullPointerException e) {
return StreamSupport.stream(Collections.singletonList(file1));
}
} else
return StreamSupport.stream(Collections.singletonList(file1));
}) //Here I got all the 2 depth and 3 depth folders
.filter(o -> listOfExtFolders.contains(o.getName().toLowerCase()))
.findFirst();
optional.ifPresent(file -> thePath[0] = file.getAbsolutePath());
Log.i("Path", thePath[0]);
return thePath[0];
}
Sd カードのパスが見つからない場合、このメソッドは空の文字列を返します。