android下如何将u盘文件到时sd卡,android获取外接SD卡或者U盘路径方法

最近在开发androidTV时遇到插U盘获取U盘内容的需求,但是按照传统的 Environment.getExternalStorageDirectory()只能读取到插入的SD卡的路径,如果是U盘的话无法读出U盘的路径。

在网上找了很久,始终没有找到合适的,也有说通过监听U盘的挂载事件,获取的感兴趣的可以自己查找一下。

最终在一个在CSDN的论坛里找到相关的东西,就试了下直接通脱StorageManager获取存储路径的。

核心如下,volumePaths的数组就是系统外接设备的路径,经过测试的确是挂载的路径。不过有些事不可用的,它只是列出了系统可支持的外接路径。

StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);

String[] volumePaths = (String[]) sm.getClass().getMethod("getVolumePaths", null).invoke(sm, null);

由于需求是优先取有指定目录(外接设备中包含testdir文件夹)的且可用的路径所以下面是我的实现方法:

/**

* 获取缓存根路径

* @param context

* @return

*/

public static String getCacheDir(Context context) {

String cachFileRootDir = "";

try {

StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);

String[] volumePaths = (String[]) sm.getClass().getMethod("getVolumePaths", null).invoke(sm, null);

if (volumePaths != null && volumePaths.length > 0) {

for (String sdcardPath : volumePaths) {

File file = new File(sdcardPath+"/testdir");

if(file.exists() && file.isDirectory()){

cachFileRootDir = sdcardPath+"/testdir";

break;

}

}

if(StringUtil.isBlank(cachFileRootDir)){

for(String sdcardPath: volumePaths){

File file = new File(sdcardPath+"/testdir");

try{

file.mkdirs();

}catch(Exception e){

e.printStackTrace();

}

file = new File(sdcardPath+"/testdir");

if(file.exists() && file.isDirectory()){

cachFileRootDir = sdcardPath+"/testdir";

break;

}

}

}

}

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

} catch (NoSuchMethodException e) {

e.printStackTrace();

}

if(StringUtil.isBlank(cachFileRootDir)){

cachFileRootDir = Environment.getExternalStorageDirectory()+"/testdir";

}

return cachFileRootDir;

}

如果想要所有实际连接的路径,也可以用我的笨办法,在路径底下创建一个文件或者文件夹,看它是否创建成功,如果创建成功,就证明是可用的。也就是:

for(String sdcardPath: volumePaths){

File file = new File(sdcardPath+"/testdir");

try{

file.mkdirs();

}catch(Exception e){

e.printStackTrace();

}

file = new File(sdcardPath+"/testdir");

if(file.exists() && file.isDirectory()){

cachFileRootDir = sdcardPath+"/testdir";

break;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值