当前位置: 移动技术网 > IT编程>移动开发>Android > 操作SD卡中文件夹和文件的方法

操作SD卡中文件夹和文件的方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

巴里亚曼废墟,尖叫皇后第一季,狗窝网

文件夹的创建

复制代码 代码如下:

        file file = environment.getexternalstoragedirectory();
        file file_0 = new file(file, "file_demo");
          if (!file_0.exists()) {
              file_0.mkdirs();
           }


 创建文件夹的时候,需要<uses-permission android:name="android.permission.write_external_storage" />权限,

        否则会报如下错误:

applicationcontext unable to create external files directory

 这里建议使用mkdirs()创建文件夹,而不是用mkdir(),因为前者可以同时创建父文件夹,如果不存在的话,而后者不能。

文件的创建      

复制代码 代码如下:

                     file file = environment.getexternalstoragedirectory();
                      file file_0 = new file(file, "pic");
                         if (!file_0.exists()) {
                                file_0.mkdirs();
                         }
                      try {
                          file pic = new file(file_0, "pic.png");
                      inputstream is = getresources().openrawresource(
                                                            r.drawable.ic_launcher);
                      outputstream os = new fileoutputstream(pic);
                      byte[] data = new byte[is.available()];
                      is.read(data);
                      os.write(data);
                      is.close();
                      os.close();
                      } catch (filenotfoundexception e) {
                         // todo auto-generated catch block
                      e.printstacktrace();
                      } catch (ioexception e) {
                       // todo auto-generated catch block
                             e.printstacktrace();
                      }


创建的文件名不能带有.后缀的,否则会报如下错误:

java.io.filenotfoundexception:/mnt/sdcard/pic/pic.png (is a directory)

同时在对文件夹的读写操作时最好添加如下权限:

复制代码 代码如下:

 <uses-permission android:name="android.permission.mount_unmount_filesystems" />
 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网