android文件读写总结

来源:互联网 发布:小猫多少钱一只淘宝网 编辑:程序博客网 时间:2024/05/16 03:27

android中文件放的位置不同,读取的方式也不太一样

1.资源文件的读取(raw和asset)

a.得到资源中的数据流

InputStream in = getResources().openRawResource(R.raw.test);

InputStream in = getResources().getAssets().open(fileName);

b.得到数据的大小

int length = in.available();

byte[] buffer = new byte[length];

c.读取数据

in.read(buffer);

d.转码,关闭流

String res = EncodingUtils.getString(buffer,"BIG5");

in.close();

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

读取  FileInputStream fin = context.openFileInput(fileName);

写入  FileOutputStream fout = context.openFileOutput(fileName,MODE_PRIVATE);

3.读写/mnt/sdcard/目录下文件

        SD卡中的文件使用FileInputStream和FileOutputStream进行文件的操作。
        存放在数据区(/data/data/..)的文件只能使用openFileOutput和openFileInput进行操作。

4.apk资源文件超过1MB的处理

       我们可以将这个数据再复制到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;    }


0 0
原创粉丝点击