Android进阶之路——文件读写

作者: SingleoD | 来源:发表于2016-06-16 19:48 被阅读8495次

    今天Leo要给大家总结一些关于Android文件读写的操作,在大家遇到关于这方面的问题,就不用东拼西凑的百度来百度去的,好了,话不多说,切入正题。

    一、概要

    1. apk中有两种资源文件,raw下的和assert下的,这些数据只能读取,不能写入。更重要的是该目录下的文件大小不能超过1M。

    2. SD卡中的文件使用FileInputStream和FileOutputStream进行文件的操作。

    3. 存放在数据区(/data/data/..)的文件只能使用openFileOutput和openFileInput进行操作。注意这里不能使用FileInputStream和FileOutputStream进行文件的操作。

    二、读写方式

    1. 资源文件(只读)两种资源文件,使用两种不同的方式进行打开使用。
      raw使用InputStream in = getResources().openRawResource(R.raw.test);
      asset使用InputStream in = getResources().getAssets().open(fileName);
      注:在使用InputStream的时候需要在函数名称后加上throws IOException。

    2. 数据区文件(/data/data/<应用程序名>目录上的文件)
      (1)写操作:
      FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);
      (2)读操作:FileInputStream fin = openFileInput(fileName);
      (3)写操作中的使用模式:
      MODE_APPEND:即向文件尾写入数据
      MODE_PRIVATE:即仅打开文件可写入数据
      MODE_WORLD_READABLE:所有程序均可读该文件数据
      MODE_WORLD_WRITABLE:即所有程序均可写入数据。

    3. sdcard数据
      (1)读操作
      FileInputStream fin = new FileInputStream(fileName);
      (2)写操作
      FileOutputStream fout = new FileOutputStream(fileName);
      (3)必要步骤
      ①获取权限
      A 获取文件创建修改权限

      Paste_Image.png
      B 可写
      Paste_Image.png
      ②检查内存状态(是否安装sd卡)
      if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
      ③读写操作
      关于sdcard
      注意:访问SDCard必须在AndroidManifest.xml中加入访问SDCard的权限
      if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
      File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
      File saveFile = new File(sdCardDir, “a.txt”);
      FileOutputStream outStream = new FileOutputStream(saveFile);
      outStream.write(“test”.getBytes());
      outStream.close();
      }
      Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED。

    Environment.getExternalStorageDirectory()方法用于获取SDCard的目录,当然要获取SDCard的目录,你也可以这样写:
    File sdCardDir = new File(“/sdcard”); //获取SDCard目录
    File saveFile = new File(sdCardDir, “itcast.txt”);
    上面两句代码可以合成一句:
    File saveFile = new File(“/sdcard/a.txt”);
    FileInputStream是InputStream的子类

    三、文件读写代码示例

    ⒈ 资源文件的读取:

    ① 从resource的raw中读取文件数据:

    String res = ""; 
    try{ 
    
    //得到资源中的Raw数据流
    InputStream in = getResources().openRawResource(R.raw.test); 
    
    //得到数据的大小
    int length = in.available();       
    
    byte [] buffer = new byte[length];        
    
    //读取数据
    in.read(buffer);         
    
    //依test.txt的编码类型选择合适的编码,如果不调整会乱码 
    res = EncodingUtils.getString(buffer, "BIG5"); 
    
    //关闭    
    in.close();            
    
     }catch(Exception e){ 
      e.printStackTrace();         
     } 
    

    ② 从resource的asset中读取文件数据:

     String fileName = "test.txt"; //文件名字 
     String res=""; 
      try{ 
    
      //得到资源中的asset数据流
      InputStream in = getResources().getAssets().open(fileName); 
    
      int length = in.available();         
      byte [] buffer = new byte[length];        
    
      in.read(buffer);            
      in.close();
      res = EncodingUtils.getString(buffer, "UTF-8");     
    
      }catch(Exception e){ 
    
      e.printStackTrace();         
    
      } 
    

    2. 读写/data/data/<应用程序名>目录上的文件:

      //写数据
     public void writeFile(String fileName,String writestr) throws IOException{ 
      try{ 
    
        FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE); 
    
        byte [] bytes = writestr.getBytes(); 
    
        fout.write(bytes); 
    
        fout.close(); 
      } 
    
      catch(Exception e){ 
            e.printStackTrace(); 
      } 
     } 
    
    //读数据
    public String readFile(String fileName) throws IOException{ 
        String res=""; 
        try{ 
             FileInputStream fin = openFileInput(fileName); 
             int length = fin.available(); 
             byte [] buffer = new byte[length]; 
             fin.read(buffer);     
             res = EncodingUtils.getString(buffer, "UTF-8"); 
             fin.close();     
         } 
         catch(Exception e){ 
             e.printStackTrace(); 
         } 
         return res; 
         }   
    

    3.读写SD卡中的文件(也就是/mnt/sdcard/目录下面的文件):

        //写数据到SD中的文件
     public void writeFileSdcardFile(String fileName,String write_str) throws IOException{ 
     try{ 
    
       FileOutputStream fout = new FileOutputStream(fileName); 
       byte [] bytes = write_str.getBytes(); 
    
       fout.write(bytes); 
       fout.close(); 
     }
    
      catch(Exception e){ 
        e.printStackTrace(); 
       } 
     } 
    
    
        //读SD中的文件
      public String readFileSdcardFile(String fileName) throws IOException{ 
      String res=""; 
      try{ 
         FileInputStream fin = new FileInputStream(fileName); 
    
         int length = fin.available(); 
    
         byte [] buffer = new byte[length]; 
         fin.read(buffer);     
    
         res = EncodingUtils.getString(buffer, "UTF-8"); 
    
         fin.close();     
        } 
    
        catch(Exception e){ 
         e.printStackTrace(); 
        } 
        return res; 
        } 
    

    4. 使用File类进行文件的读写:

      //读文件
      public String readSDFile(String fileName) throws IOException {  
    
        File file = new File(fileName);  
    
        FileInputStream fis = new FileInputStream(file);  
    
        int length = fis.available(); 
    
         byte [] buffer = new byte[length]; 
         fis.read(buffer);     
    
         res = EncodingUtils.getString(buffer, "UTF-8"); 
    
         fis.close();     
         return res;  
      }  
    
      //写文件
      public void writeSDFile(String fileName, String write_str) throws IOException{  
    
        File file = new File(fileName);  
    
        FileOutputStream fos = new FileOutputStream(file);  
    
        byte [] bytes = write_str.getBytes(); 
    
        fos.write(bytes); 
    
        fos.close(); 
      } 
    

    5. 另外,File类还有下面一些常用的操作:

      String Name = File.getName();  //获得文件或文件夹的名称:
      String parentPath = File.getParent();  //获得文件或文件夹的父目录
      String path = File.getAbsoultePath();//绝对路经
      String path = File.getPath();//相对路经 
      File.createNewFile();//建立文件  
      File.mkDir(); //建立文件夹  
      File.isDirectory(); //判断是文件或文件夹
      File[] files = File.listFiles();  //列出文件夹下的所有文件和文件夹名
      File.renameTo(dest);  //修改文件夹和文件名
      File.delete();  //删除文件夹或文件
    

    6. 如何从FileInputStream中得到InputStream?

      public String readFileData(String fileName) throws IOException{ 
      String res=""; 
      try{ 
         FileInputStream fin = new FileInputStream(fileName); 
         InputStream in = new BufferedInputStream(fin);
    
         ...
    
      }
      catch(Exception e){ 
         e.printStackTrace(); 
      }
    
      }
    

    7. APK资源文件的大小不能超过1M,如果超过了怎么办?

    我们可以将这个数据再复制到data目录下,然后再使用。复制数据的代码如下:

        public boolean assetsCopyData(String strAssetsFilePath, String strDesFilePath){
           boolean bIsSuc = true;
           InputStream inputStream = null;
           OutputStream outputStream = null;
           
           File file = new File(strDesFilePath);
           if (!file.exists()){
               try {
                  file.createNewFile();
                  Runtime.getRuntime().exec("chmod 766 " + file);
               } catch (IOException e) {
                  bIsSuc = false;
               }
               
           }else{//存在
               return true;
           }
           
           try {
               inputStream = getAssets().open(strAssetsFilePath);
               outputStream = new FileOutputStream(file);
               
               int nLen = 0 ;
               
               byte[] buff = new byte[1024*1];
               while((nLen = inputStream.read(buff)) > 0){
                  outputStream.write(buff, 0, nLen);
               }
               
               //完成
           } catch (IOException e) {
               bIsSuc = false;
           }finally{
               try {
                  if (outputStream != null){
                      outputStream.close();
                  }
                  
                  if (inputStream != null){
                      inputStream.close();
                  }
               } catch (IOException e) {
                  bIsSuc = false;
               }
               
           }
           
           return bIsSuc;
        }   
    

    [详细参考] (http://blog.csdn.net/ztp800201/article/details/7322110)

    对于Android文件读写,leo就给大家介绍到这了,如有什么补充建议的地方,欢迎提出指正,喜欢的话,就点个赞吧……

    相关文章

      网友评论

      • pokerfaceCmy:EncodingUtils是什么
        53f2f1535377:@SingleoD 这个工具类在Android6.0就移除了 现在用new String(str,"UTF-8")这种构造方法可以适用所有版本
        SingleoD:系统的一个工具类,这个类的getstring方法用于选择合适的编码类型,不然会出现乱码
      • 83160b2715da:挺好
        SingleoD: @坏河豚 谢谢

      本文标题:Android进阶之路——文件读写

      本文链接:https://www.haomeiwen.com/subject/bnwmdttx.html