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

时间:2021-08-11 07:39:13

文件夹的创建

复制代码 代码如下:

        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" />