Android进阶之路——文件读写

今天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就给大家介绍到这了,如有什么补充建议的地方,欢迎提出指正,喜欢的话,就点个赞吧……

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容

  • permissionn.允许;批准,正式认可,认可user permission 使用权限permission D...
    lengol阅读 1,042评论 0 51
  • Android开发中,离不开对文件的操作。本文首先介绍了使用java对文件进行基本的读写操作,而后介绍了A...
    baolvlv阅读 11,969评论 0 5
  • 一、流的概念和作用。 流是一种有顺序的,有起点和终点的字节集合,是对数据传输的总成或抽象。即数据在两设备之间的传输...
    布鲁斯不吐丝阅读 10,045评论 2 95
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,432评论 0 17
  • 前几天听到了奇然唱琵琶行,毕业很久的我又背起了琵琶行,不一样的感觉,余音绕梁。 向高三党强烈推荐这首歌, 背诗有奇效啊!
    萍果派阅读 627评论 0 2