三星Galaxy S3有一个extrenal SD卡插槽,安装在/mnt/extSdCard
。
我的问题是:如何通过类似Environment.getExternalStorageDirectory()
的方式获取此路径?这将返回mnt/sdcard
,我找不到外部SD卡的API。 (或某些平板电脑上的可移动USB存储设备)
谢谢!
答案 0 :(得分:55)
我找到了here
的解决方案的变体public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
原始方法已经过测试并与
一起使用我不确定测试时这些是哪个Android版本。
我用
测试了我的修改版本以及一些使用SD卡作为主存储的单个存储设备
除了令人难以置信的所有这些设备只返回了他们的可移动存储。我可能会做一些额外的检查,但这至少比我迄今为止找到的任何解决方案都要好一些。
答案 1 :(得分:52)
我找到了更可靠的方法来获取系统中所有SD-CARD的路径。 这适用于所有Android版本并返回所有存储的路径(包括模拟)。
在我的所有设备上正常运行。
P.S。:基于环境类的源代码。
private static final Pattern DIR_SEPORATOR = Pattern.compile("/");
/**
* Raturns all available SD-Cards in the system (include emulated)
*
* Warning: Hack! Based on Android source code of version 4.3 (API 18)
* Because there is no standart way to get it.
* TODO: Test on future Android versions 4.4+
*
* @return paths to all available SD-Cards in the system (include emulated)
*/
public static String[] getStorageDirectories()
{
// Final set of paths
final Set<String> rv = new HashSet<String>();
// Primary physical SD-CARD (not emulated)
final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
// All Secondary SD-CARDs (all exclude primary) separated by ":"
final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
// Primary emulated SD-CARD
final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
if(TextUtils.isEmpty(rawEmulatedStorageTarget))
{
// Device has physical external storage; use plain paths.
if(TextUtils.isEmpty(rawExternalStorage))
{
// EXTERNAL_STORAGE undefined; falling back to default.
rv.add("/storage/sdcard0");
}
else
{
rv.add(rawExternalStorage);
}
}
else
{
// Device has emulated storage; external storage paths should have
// userId burned into them.
final String rawUserId;
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
{
rawUserId = "";
}
else
{
final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
final String[] folders = DIR_SEPORATOR.split(path);
final String lastFolder = folders[folders.length - 1];
boolean isDigit = false;
try
{
Integer.valueOf(lastFolder);
isDigit = true;
}
catch(NumberFormatException ignored)
{
}
rawUserId = isDigit ? lastFolder : "";
}
// /storage/emulated/0[1,2,...]
if(TextUtils.isEmpty(rawUserId))
{
rv.add(rawEmulatedStorageTarget);
}
else
{
rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
}
}
// Add all secondary storages
if(!TextUtils.isEmpty(rawSecondaryStoragesStr))
{
// All Secondary SD-CARDs splited into array
final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
Collections.addAll(rv, rawSecondaryStorages);
}
return rv.toArray(new String[rv.size()]);
}
答案 2 :(得分:31)
我想使用外部SD卡需要使用它:
new File("/mnt/external_sd/")
OR
new File("/mnt/extSdCard/")
在你的情况下...
替换Environment.getExternalStorageDirectory()
适合我。您应该首先检查目录mnt中的内容,然后从那里开始工作..
您应该使用某种类型的选择方法来选择使用哪个SD卡:
File storageDir = new File("/mnt/");
if(storageDir.isDirectory()){
String[] dirList = storageDir.list();
//TODO some type of selecton method?
}
答案 3 :(得分:15)
要检索所有External Storages(无论是 SD卡 还是 内部不可移动存储空间 ),您可以使用以下代码:
final String state = Environment.getExternalStorageState();
if ( Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) { // we can read the External Storage...
//Retrieve the primary External Storage:
final File primaryExternalStorage = Environment.getExternalStorageDirectory();
//Retrieve the External Storages root directory:
final String externalStorageRootDir;
if ( (externalStorageRootDir = primaryExternalStorage.getParent()) == null ) { // no parent...
Log.d(TAG, "External Storage: " + primaryExternalStorage + "\n");
}
else {
final File externalStorageRoot = new File( externalStorageRootDir );
final File[] files = externalStorageRoot.listFiles();
for ( final File file : files ) {
if ( file.isDirectory() && file.canRead() && (file.listFiles().length > 0) ) { // it is a real directory (not a USB drive)...
Log.d(TAG, "External Storage: " + file.getAbsolutePath() + "\n");
}
}
}
}
或者,您可以使用 System.getenv(“EXTERNAL_STORAGE”)来检索主外部存储目录(例如“/ storage / sdcard0”)和 System.getenv(“SECONDARY_STORAGE”)以撤消所有辅助目录的列表(例如“/ storage / extSdCard:/ storage / UsbDriveA:/ storage / UsbDriveB”)。请记住,在这种情况下,您可能希望过滤辅助目录列表以排除USB驱动器。
在任何情况下,请注意使用硬编码路径始终是一种不好的方法(尤其是当每个制造商都可能会高兴地更改它时)。
答案 4 :(得分:14)
我正在使用 Dmitriy Lozenko 的解决方案,直到我检查了 Asus Zenfone2 , Marshmallow 6.0.1 以及解决方案不管用。获得 EMULATED_STORAGE_TARGET 时解决方案失败,特别是对于microSD路径,即: / storage / F99C-10F4 / 。我编辑了代码以直接从模拟的应用程序路径context.getExternalFilesDirs(null);
获取模拟根路径,并添加更多已知的特定于电话模型的物理路径。
为了让我们的生活更轻松,我建立了一个图书馆here。您可以通过gradle,maven,sbt和leiningen构建系统使用它。
如果你喜欢老式的方式,你也可以直接从here复制粘贴文件,但是如果没有手动检查,你将不知道将来是否有更新。
如果您有任何问题或建议,请告诉我
答案 5 :(得分:12)
新的Context.getExternalFilesDirs()
和Context.getExternalCacheDirs()
方法可以返回多个路径,包括主设备和辅助设备。然后,您可以迭代它们并检查Environment.getStorageState()
和File.getFreeSpace()
以确定存储文件的最佳位置。这些方法也可以在support-v4库中的ContextCompat
上使用。
另请注意,如果您只对使用Context
返回的目录感兴趣,则不再需要READ_
或WRITE_EXTERNAL_STORAGE
权限。展望未来,您将始终拥有对这些目录的读/写权限,而无需其他权限。
应用还可以通过终止其权限请求继续使用旧设备:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
答案 6 :(得分:9)
以下是我获取SD卡路径列表(主外部存储空间除外)的方法:
/**
* returns a list of all available sd cards paths, or null if not found.
*
* @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static List<String> getSdCardPaths(final Context context,final boolean includePrimaryExternalStorage)
{
final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
if(externalCacheDirs==null||externalCacheDirs.length==0)
return null;
if(externalCacheDirs.length==1)
{
if(externalCacheDirs[0]==null)
return null;
final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
if(!Environment.MEDIA_MOUNTED.equals(storageState))
return null;
if(!includePrimaryExternalStorage&&VERSION.SDK_INT>=VERSION_CODES.HONEYCOMB&&Environment.isExternalStorageEmulated())
return null;
}
final List<String> result=new ArrayList<>();
if(includePrimaryExternalStorage||externalCacheDirs.length==1)
result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
for(int i=1;i<externalCacheDirs.length;++i)
{
final File file=externalCacheDirs[i];
if(file==null)
continue;
final String storageState=EnvironmentCompat.getStorageState(file);
if(Environment.MEDIA_MOUNTED.equals(storageState))
result.add(getRootOfInnerSdCardFolder(externalCacheDirs[i]));
}
if(result.isEmpty())
return null;
return result;
}
/** Given any file/folder inside an sd card, this will return the path of the sd card */
private static String getRootOfInnerSdCardFolder(File file)
{
if(file==null)
return null;
final long totalSpace=file.getTotalSpace();
while(true)
{
final File parentFile=file.getParentFile();
if(parentFile==null||parentFile.getTotalSpace()!=totalSpace)
return file.getAbsolutePath();
file=parentFile;
}
}
答案 7 :(得分:9)
我做了以下操作来访问所有外部SD卡。
使用:
File primaryExtSd=Environment.getExternalStorageDirectory();
您将获得主外部SD的路径 然后用:
File parentDir=new File(primaryExtSd.getParent());
您获得主外部存储的父目录,并且它也是所有外部sd的父目录。 现在,您可以列出所有存储并选择您想要的存储。
希望它有用。
答案 8 :(得分:5)
感谢你们提供的线索,特别是@SmartLemon,我得到了解决方案。如果其他人需要它,我把我的最终解决方案放在这里(找到第一个列出的外部SD卡):
public File getExternalSDCardDirectory()
{
File innerDir = Environment.getExternalStorageDirectory();
File rootDir = innerDir.getParentFile();
File firstExtSdCard = innerDir ;
File[] files = rootDir.listFiles();
for (File file : files) {
if (file.compareTo(innerDir) != 0) {
firstExtSdCard = file;
break;
}
}
//Log.i("2", firstExtSdCard.getAbsolutePath().toString());
return firstExtSdCard;
}
如果没有外部SD卡,则返回板载存储。如果sdcard不存在我会使用它,你可能需要更改它。
答案 9 :(得分:3)
参考我的代码,希望对您有所帮助:
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
String mount = new String();
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//TF card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat("*" + columns[1] + "\n");
}
} else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat(columns[1] + "\n");
}
}
}
txtView.setText(mount);
答案 10 :(得分:2)
这个解决方案(从这个问题的其他答案中汇总而来)处理了事实(正如@ono所提到的)System.getenv("SECONDARY_STORAGE")
对Marshmallow毫无用处。
经过测试和处理:
三星Galaxy Tab A(Android 6.0.1 - 股票)
/**
* Returns all available external SD-Card roots in the system.
*
* @return paths to all available external SD-Card roots in the system.
*/
public static String[] getStorageDirectories() {
String [] storageDirectories;
String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
List<String> results = new ArrayList<String>();
File[] externalDirs = applicationContext.getExternalFilesDirs(null);
for (File file : externalDirs) {
String path = file.getPath().split("/Android")[0];
if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Environment.isExternalStorageRemovable(file))
|| rawSecondaryStoragesStr != null && rawSecondaryStoragesStr.contains(path)){
results.add(path);
}
}
storageDirectories = results.toArray(new String[0]);
}else{
final Set<String> rv = new HashSet<String>();
if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
Collections.addAll(rv, rawSecondaryStorages);
}
storageDirectories = rv.toArray(new String[rv.size()]);
}
return storageDirectories;
}
答案 11 :(得分:2)
是。不同厂商使用不同的SD卡名称,如三星Tab 3中的extsd,以及其他三星设备使用sdcard这样不同的厂商使用不同的名称。
我和你有同样的要求。所以我已经从我的项目中为您创建了一个示例示例,转到此链接Android Directory chooser示例,该示例使用了androi-dirchooser库。此示例检测SD卡并列出所有子文件夹,它还检测设备是否有多于一张SD卡。
部分代码如下所示。完整示例转到链接Android Directory Chooser
/**
* Returns the path to internal storage ex:- /storage/emulated/0
*
* @return
*/
private String getInternalDirectoryPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
/**
* Returns the SDcard storage path for samsung ex:- /storage/extSdCard
*
* @return
*/
private String getSDcardDirectoryPath() {
return System.getenv("SECONDARY_STORAGE");
}
mSdcardLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String sdCardPath;
/***
* Null check because user may click on already selected buton before selecting the folder
* And mSelectedDir may contain some wrong path like when user confirm dialog and swith back again
*/
if (mSelectedDir != null && !mSelectedDir.getAbsolutePath().contains(System.getenv("SECONDARY_STORAGE"))) {
mCurrentInternalPath = mSelectedDir.getAbsolutePath();
} else {
mCurrentInternalPath = getInternalDirectoryPath();
}
if (mCurrentSDcardPath != null) {
sdCardPath = mCurrentSDcardPath;
} else {
sdCardPath = getSDcardDirectoryPath();
}
//When there is only one SDcard
if (sdCardPath != null) {
if (!sdCardPath.contains(":")) {
updateButtonColor(STORAGE_EXTERNAL);
File dir = new File(sdCardPath);
changeDirectory(dir);
} else if (sdCardPath.contains(":")) {
//Multiple Sdcards show root folder and remove the Internal storage from that.
updateButtonColor(STORAGE_EXTERNAL);
File dir = new File("/storage");
changeDirectory(dir);
}
} else {
//In some unknown scenario at least we can list the root folder
updateButtonColor(STORAGE_EXTERNAL);
File dir = new File("/storage");
changeDirectory(dir);
}
}
});
答案 12 :(得分:2)
实际上,在某些设备中,外部SD卡默认名称显示为extSdCard
,而其他设备显示为sdcard1
。
此代码段有助于找出确切的路径,并有助于检索外部设备的路径。
String sdpath,sd1path,usbdiskpath,sd0path;
if(new File("/storage/extSdCard/").exists())
{
sdpath="/storage/extSdCard/";
Log.i("Sd Cardext Path",sdpath);
}
if(new File("/storage/sdcard1/").exists())
{
sd1path="/storage/sdcard1/";
Log.i("Sd Card1 Path",sd1path);
}
if(new File("/storage/usbcard1/").exists())
{
usbdiskpath="/storage/usbcard1/";
Log.i("USB Path",usbdiskpath);
}
if(new File("/storage/sdcard0/").exists())
{
sd0path="/storage/sdcard0/";
Log.i("Sd Card0 Path",sd0path);
}
答案 13 :(得分:1)
在某些设备上(例如三星galaxy sII)内部存储卡可以在vfat中。在这种情况下使用参考最后一个代码,我们获得路径内部存储卡(/ mnt / sdcad)但没有外部卡。下面的代码参考解决了这个问题。
static String getExternalStorage(){
String exts = Environment.getExternalStorageDirectory().getPath();
try {
FileReader fr = new FileReader(new File("/proc/mounts"));
BufferedReader br = new BufferedReader(fr);
String sdCard=null;
String line;
while((line = br.readLine())!=null){
if(line.contains("secure") || line.contains("asec")) continue;
if(line.contains("fat")){
String[] pars = line.split("\\s");
if(pars.length<2) continue;
if(pars[1].equals(exts)) continue;
sdCard =pars[1];
break;
}
}
fr.close();
br.close();
return sdCard;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
答案 14 :(得分:1)
File[] files = null;
File file = new File("/storage");// /storage/emulated
if (file.exists()) {
files = file.listFiles();
}
if (null != files)
for (int j = 0; j < files.length; j++) {
Log.e(TAG, "" + files[j]);
Log.e(TAG, "//--//--// " + files[j].exists());
if (files[j].toString().replaceAll("_", "")
.toLowerCase().contains("extsdcard")) {
external_path = files[j].toString();
break;
} else if (files[j].toString().replaceAll("_", "")
.toLowerCase()
.contains("sdcard".concat(Integer.toString(j)))) {
// external_path = files[j].toString();
}
Log.e(TAG, "--///--///-- " + external_path);
}
答案 15 :(得分:0)
System.getenv("SECONDARY_STORAGE")
返回null。这是找到所有外部dirs的另一种方式。您可以检查它是否可移除,以确定是否内部/外部
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
File[] externalCacheDirs = context.getExternalCacheDirs();
for (File file : externalCacheDirs) {
if (Environment.isExternalStorageRemovable(file)) {
// It's a removable storage
}
}
}
答案 16 :(得分:0)
我相信这段代码一定会解决您的问题...这对我来说很好...... \
try {
File mountFile = new File("/proc/mounts");
usbFoundCount=0;
sdcardFoundCount=0;
if(mountFile.exists())
{
Scanner usbscanner = new Scanner(mountFile);
while (usbscanner.hasNext()) {
String line = usbscanner.nextLine();
if (line.startsWith("/dev/fuse /storage/usbcard1")) {
usbFoundCount=1;
Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/usbcard1" );
}
}
}
if(mountFile.exists()){
Scanner sdcardscanner = new Scanner(mountFile);
while (sdcardscanner.hasNext()) {
String line = sdcardscanner.nextLine();
if (line.startsWith("/dev/fuse /storage/sdcard1")) {
sdcardFoundCount=1;
Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/sdcard1" );
}
}
}
if(usbFoundCount==1)
{
Toast.makeText(context,"USB Connected and properly mounted", 7000).show();
Log.i("-----USB--------","USB Connected and properly mounted" );
}
else
{
Toast.makeText(context,"USB not found!!!!", 7000).show();
Log.i("-----USB--------","USB not found!!!!" );
}
if(sdcardFoundCount==1)
{
Toast.makeText(context,"SDCard Connected and properly mounted", 7000).show();
Log.i("-----SDCard--------","SDCard Connected and properly mounted" );
}
else
{
Toast.makeText(context,"SDCard not found!!!!", 7000).show();
Log.i("-----SDCard--------","SDCard not found!!!!" );
}
}catch (Exception e) {
e.printStackTrace();
}
答案 17 :(得分:0)
String secStore = System.getenv("SECONDARY_STORAGE");
File externalsdpath = new File(secStore);
这将获得外部sd二级存储的路径。
答案 18 :(得分:0)
我在三星Galaxy Tab S2(型号:T819Y)上尝试了 Dmitriy Lozenko 和 Gnathonic 提供的解决方案,但没有人帮助过我检索外部SD卡目录的路径。 mount
命令执行包含外部SD卡目录(即/ Storage / A5F9-15F4)所需的路径,但它与正则表达式不匹配,因此未返回。我没有得到三星的目录命名机制。为什么他们偏离了标准(即extsdcard),并且在我的案例(即/ Storage / A5F9-15F4)中提出了一些非常可疑的东西。有什么我想念的吗?无论如何,在 Gnathonic 解决方案的正则表达式发生变化后,我帮助我获得了有效的SD卡目录:
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*(vold|media_rw).*(sdcard|vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
我不确定这是否是一个有效的解决方案,如果它会给其他三星平板电脑的结果,但它现在解决了我的问题。以下是在Android(v6.0)中检索可移动SD卡路径的另一种方法。我用android marshmallow测试了这个方法,但它确实有效。在其中使用的方法是非常基本的,并且肯定也适用于其他版本,但测试是强制性的。对它的一些见解将有所帮助:
public static String getSDCardDirPathForAndroidMarshmallow() {
File rootDir = null;
try {
// Getting external storage directory file
File innerDir = Environment.getExternalStorageDirectory();
// Temporarily saving retrieved external storage directory as root
// directory
rootDir = innerDir;
// Splitting path for external storage directory to get its root
// directory
String externalStorageDirPath = innerDir.getAbsolutePath();
if (externalStorageDirPath != null
&& externalStorageDirPath.length() > 1
&& externalStorageDirPath.startsWith("/")) {
externalStorageDirPath = externalStorageDirPath.substring(1,
externalStorageDirPath.length());
}
if (externalStorageDirPath != null
&& externalStorageDirPath.endsWith("/")) {
externalStorageDirPath = externalStorageDirPath.substring(0,
externalStorageDirPath.length() - 1);
}
String[] pathElements = externalStorageDirPath.split("/");
for (int i = 0; i < pathElements.length - 1; i++) {
rootDir = rootDir.getParentFile();
}
File[] files = rootDir.listFiles();
for (File file : files) {
if (file.exists() && file.compareTo(innerDir) != 0) {
// Try-catch is implemented to prevent from any IO exception
try {
if (Environment.isExternalStorageRemovable(file)) {
return file.getAbsolutePath();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
如果您有任何其他方法来处理此问题,请分享。感谢
答案 19 :(得分:0)
//manifest file outside the application tag
//please give permission write this
//<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
File file = new File("/mnt");
String[] fileNameList = file.list(); //file names list inside the mnr folder
String all_names = ""; //for the log information
String foundedFullNameOfExtCard = ""; // full name of ext card will come here
boolean isExtCardFounded = false;
for (String name : fileNameList) {
if (!isExtCardFounded) {
isExtCardFounded = name.contains("ext");
foundedFullNameOfExtCard = name;
}
all_names += name + "\n"; // for log
}
Log.d("dialog", all_names + foundedFullNameOfExtCard);
答案 20 :(得分:0)
您可以使用类似的方法 - Context.getExternalCacheDirs()或Context.getExternalFilesDirs()或Context.getObbDirs()。它们在应用程序可以存储其文件的所有外部存储设备中提供特定于应用程序的目录。
这样的事情 - Context.getExternalCacheDirs()[i] .getParentFile()。getParentFile()。getParentFile()。getParent()可以获得外部存储设备的根路径。
我知道这些命令是出于不同的目的,但其他答案对我不起作用。
此链接给了我很好的指示 - https://possiblemobile.com/2014/03/android-external-storage/
答案 21 :(得分:0)
String path = Environment.getExternalStorageDirectory()
+ File.separator + Environment.DIRECTORY_PICTURES;
File dir = new File(path);
答案 22 :(得分:0)
要访问我的 SD卡中的文件,在我的HTC One X(Android)上,我使用此路径:
file:///storage/sdcard0/folder/filename.jpg
注意 tripple&#34; /&#34; !
答案 23 :(得分:0)
那不是真的。即使未安装SD卡,/ mnt / sdcard / external_sd也可以存在。当你没有挂载时尝试写入/ mnt / sdcard / external_sd时你的应用程序会崩溃。
您需要先使用以下方法检查SD卡是否已安装:
boolean isSDPresent = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
答案 24 :(得分:-1)
以下步骤对我有用。你只需要写下这一行:
---
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
---
public String login() throws Exception {
---
String URL = "https://IP//service/perform.do?operationId=XXXXX";
ClientRequest restClient = new ClientRequest(URL);
restClient.accept(MediaType.APPLICATION_JSON);
restClient.body(MediaType.APPLICATION_JSON, hmap);
ClientResponse < String > resp = restClient.post(String.class);
if (resp.getStatus() != 201) {
throw new RuntimeException("Failed : HTTPS error code : " + resp.getStatus());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(resp.getEntity().getBytes())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
return output;
}
第一行将给出sd目录的名称,您只需要在第二个字符串的replace方法中使用它。第二个字符串将包含内部和可移动 sd(在我的情况下为/ storage /)的路径。我只是为我的应用程序需要这条路径,但如果需要,你可以更进一步。
答案 25 :(得分:-1)
在Galaxy S3 Android 4.3上,我使用的路径是 ./ storage / extSdCard / Card / ,它完成了这项工作。希望它有所帮助,