前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android获取SDcard目录及创建文件夹的方法

Android获取SDcard目录及创建文件夹的方法

作者头像
砸漏
发布2020-11-05 10:44:54
2.8K0
发布2020-11-05 10:44:54
举报
文章被收录于专栏:恩蓝脚本

获取sdcard目录

代码语言:javascript
复制
 public static String getSDPath() {
    File sdDir = null;
    boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);// 判断sd卡是否存在
    if (sdCardExist) {
      sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
    }
    return sdDir.toString();
  }

创建目录,不限目录层级

代码语言:javascript
复制
public static String mkdirs(String path) {
    String sdcard = getSDPath();
    if (path.indexOf(getSDPath()) == -1) {
      path = sdcard + (path.indexOf("/") == 0 ? "" : "/") + path;
    }
    File destDir = new File(path);
    if (!destDir.exists()) {
      path = makedir(path);
      if (path == null) {
        return null;
      }
    }
    return path;
  }

  private static String makedir(String path) {
    String sdPath = getSDPath();
    String[] dirs = path.replace(sdPath, "").split("/");
    StringBuffer filePath = new StringBuffer(sdPath);
    for (String dir : dirs) {
      if (!"".equals(dir) && !dir.equals(sdPath)) {
        filePath.append("/").append(dir);
        File destDir = new File(filePath.toString());
        if (!destDir.exists()) {
          boolean b = destDir.mkdirs();
          if (!b) {
            return null;
          }
        }
      }
    }
    return filePath.toString();
  }

所需权限

代码语言:javascript
复制
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" / 
<!-- 在sdcard中创建/删除文件的权限 -- 
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" / 

显示本地图片

代码语言:javascript
复制
ImageView view5 = findView(R.id.imageview2);
view5.setImageBitmap(ImageUtils.getLoacalBitmap("/storage/sdcard1/myimage/20160807.jpg"));

public static Bitmap getLoacalBitmap(String url) {
    try {
       FileInputStream fis = new FileInputStream(url);
       return BitmapFactory.decodeStream(fis);
    } catch (FileNotFoundException e) {
       //这里应显示默认图片,如图片无法显示等;从应用资源图片中选取
       return null;
    }
  }

以上这篇Android获取SDcard目录及创建文件夹的方法就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档