您的位置:首页 > 移动开发 > Android开发

Android读取本地存储和SD卡文件

2016-08-22 16:16 435 查看
功能:判断内置sd卡(本地内存)和sd卡是否有某文件。我这里是如果有某文件,按钮显示,如果本地和sd卡都没有,则隐藏。

btn_main.setVisibility(isShow() ? View.VISIBLE : View.GONE);
在是否需要显示的地方判断。


public boolean isShow() {
//判断sd卡是否存在,并且是否具有读写权限
File file = new File(Environment.getExternalStorageDirectory(),
"ZYSJ/Offline/zy.tpk");
if (file.exists()) {
AppConstant.OfflineMapPATH = file.getAbsolutePath();
return true;
}
file = getSDCard();
if (file != null) {
AppConstant.OfflineMapPATH = file.getAbsolutePath();
return true;
}
}
return false;
}


判断是否存在,如果本地存在,直接返回true,按钮显示;如果本地没有,再去sd卡找。

/**
* 获取外置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;
}

private File getSDCard() {
List<String> cardPath = getExtSDCardPath();//这个方法是获取sd卡的路径个数
File file = null;
if (cardPath != null && cardPath.size() >= 1) {//可能不止一张卡,循环遍历查找
File path = new File(cardPath.get(0), "ZYSJ/Offline/zy.tpk");
if (path.exists()) {
file = path;
}
}
return file;
}


//文件路径
public static String OfflinePATH = null;
在AppConstant里面定义。进行上述那些判断的原因是如果检测到本地或sd卡已经存在,则把之前保留的直接赋值就好,无需每次执行查询代码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: