android系统可通过Environment.getExternalStorageDirectory()获取存储卡的路径,但是现在有很多手机内置有一个存储空间,同时还支持外置sd卡插入,这样通过Environment.getExternalStorageDirectory()方法获取到的就是内置存储卡的位置,需要获取外置存储卡的路径就比较麻烦,这里借鉴网上的代码,稍作修改,在已有的手机上做了测试,效果还可以,当然也许还有其他的一些奇葩机型没有覆盖到。
package com.example.getpath; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.util.Log; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getPath2(); } @SuppressLint("SdCardPath") public String getPath2() { String sdcard_path = null; String sd_default = Environment.getExternalStorageDirectory() .getAbsolutePath(); Log.d("text", sd_default); if (sd_default.endsWith("/")) { sd_default = sd_default.substring(0, sd_default.length() - 1); } // 得到路径 try { Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("mount"); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); String line; BufferedReader br = new BufferedReader(isr); while ((line = br.readLine()) != null) { if (line.contains("secure")) continue; if (line.contains("asec")) continue; if (line.contains("fat") && line.contains("/mnt/")) { String columns[] = line.split(" "); if (columns != null && columns.length > 1) { if (sd_default.trim().equals(columns[1].trim())) { continue; } sdcard_path = columns[1]; } } else if (line.contains("fuse") && line.contains("/mnt/")) { String columns[] = line.split(" "); if (columns != null && columns.length > 1) { if (sd_default.trim().equals(columns[1].trim())) { continue; } sdcard_path = columns[1]; } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("text", sdcard_path); return sdcard_path; } }
原文链接:http://www.90159.com/2015/06/15/Android获取系统外置存储卡路径的方法/?utm_source=tuicool