android获取内置和外置SD卡路径 - z
Posted 行者-慧超
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android获取内置和外置SD卡路径 - z相关的知识,希望对你有一定的参考价值。
本文将介绍Android真机环境下如何获取内置和外置SD卡路径。
测试环境:三星Note3,其他手机待测试。。。
所需权限(androidManifest.xml文件里)
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
获取路径代码(MainActivity.java文件)
- package com.example.androidtest;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.List;
- import android.os.Bundle;
- import android.os.Environment;
- import android.app.Activity;
- import android.view.Menu;
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- StringBuilder log = new StringBuilder();
- String inPath = getInnerSDCardPath();
- log.append("内置SD卡路径:" + inPath + "\r\n");
- List<String> extPaths = getExtSDCardPath();
- for (String path : extPaths) {
- log.append("外置SD卡路径:" + path + "\r\n");
- }
- System.out.println(log.toString());
- }
- /**
- * 获取内置SD卡路径
- * @return
- */
- public String getInnerSDCardPath() {
- return Environment.getExternalStorageDirectory().getPath();
- }
- /**
- * 获取外置SD卡路径
- * @return 应该就一条记录或空
- */
- public List<String> getExtSDCardPath()
- {
- List<String> lResult = new ArrayList<String>();
- try {
- Runtime rt = Runtime.getRuntime();
- Process proc = rt.exec("mount");
- InputStream is = proc.getInputStream();
- InputStreamReader isr = new InputStreamReader(is);
- BufferedReader br = new BufferedReader(isr);
- String line;
- while ((line = br.readLine()) != null) {
- if (line.contains("extSdCard"))
- {
- String [] arr = line.split(" ");
- String path = arr[1];
- File file = new File(path);
- if (file.isDirectory())
- {
- lResult.add(path);
- }
- }
- }
- isr.close();
- } catch (Exception e) {
- }
- return lResult;
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- }
其中,line.contains("extSdCard")判断部分有待进一步验证!
打印结果:
1. 插入一张外置SD卡后
- 内置SD卡路径:/storage/emulated/0
- 外置SD卡路径:/storage/extSdCard
2. 取出外置SD卡后
- 内置SD卡路径:/storage/emulated/0
以上是关于android获取内置和外置SD卡路径 - z的主要内容,如果未能解决你的问题,请参考以下文章