Android编程之文件读写操作与技巧总结【经典收藏】

2019-12-10 17:48:32王冬梅

七、读取资源文件时能否实现类似于seek的方式可以跳转到文件的任意位置,从指定的位置开始读取指定的字节数呢?
答案是可以的。

在FileInputStream和InputStream中都有下面的函数:

public long skip (long byteCount); //从数据流中跳过n个字节
public int read (byte[] buffer, int offset, int length); //从数据流中读取length数据存在buffer的offset开始的位置。offset是相对于buffer的开始位置的,不是数据流。

可以使用这两个函数来实现类似于seek的操作,请看下面的测试代码:

//其中read_raw是一个txt文件,存放在raw目录下。
//read_raw.txt文件的内容是:"ABCDEFGHIJKLMNOPQRST"
public String getRawString() throws IOException {
  String str = null;
  InputStream in = getResources().openRawResource(R.raw.read_raw);
  int length = in.available();
  byte[] buffer = new byte[length];
  in.skip(2); //跳过两个字节
  in.read(buffer,0,3); //读三个字节
  in.skip(3); //跳过三个字节
  in.read(buffer,0,3); //读三个字节
  //最后str="IJK"
  str = EncodingUtils.getString(buffer, "BIG5");
  in.close();
  return str;
}

从上面的实例可以看出skip函数有点类似于C语言中的seek操作,但它们之间有些不同。

需要注意的是:

1、skip函数始终是从当前位置开始跳的。在实际应用当中还要再判断一下该函数的返回值。

2、read函数也始终是当前位置开始读的。

3、另外,还可以使用reset函数将文件的当前位置重置为0,也就是文件的开始位置。

如何得到文件的当前位置?

我没有找到相关的函数和方法,不知道怎么样才能得到文件的当前位置,貌似它也并不是太重要。

八、如何从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();
   }
}

九、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;
}