Android: Accessing File from Internal Storage Using RandomAccessFile

南楼画角 提交于 2019-12-01 22:00:01

1- Copy the file from assets to the cache directory

This code just for illustration, you have to do appropriate exception handling and close resources

private File createCacheFile(Context context, String filename){
  File cacheFile = new File(context.getCacheDir(), filename);

  if (cacheFile.exists()) {
      return cacheFile ;
  }


  InputStream inputStream = context.getAssets().open(filename);
  FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);

  int bufferSize = 1024;
  byte[] buffer = new byte[bufferSize];
  int length = -1;
  while ( (length = inputStream.read(buffer)) > 0) {
     fileOutputStream.write(buffer,0,length);
  }

  fileOutputStream.close();
  inputStream.close();

  return cacheFile;
}

2- Open the file using RandomAccessFile

File cacheFile = createCacheFile(context, "text.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(cacheFile, "r");

// Process the file

randomAccessFile.close();    

On a side note, you should follow Java naming conventions, e.g. your method and variable name should start with small letter such as copyFromAssetsToStorage and destinationFile

Edit:

You should make a separate try/catch for each close() operation, so if one fails the other still get executed and check that they are not null

finally {
    try {
       if(fileOutputStream!=null){
          fileOutputStream.close();            
       }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
      if(inputStream!=null){
       inputStream.close();      
      }      
    } catch (IOException e) {
        e.printStackTrace();
    }
}  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!