Android: Accessing File from Internal Storage Using RandomAccessFile

后端 未结 1 1269
南方客
南方客 2021-01-21 02:05

I am creating an app that needs to read data from a file. I was initially reading it from the assets folder using a BufferedReader and an InputStreamReader

相关标签:
1条回答
  • 2021-01-21 02:49

    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();
        }
    }  
    
    0 讨论(0)
提交回复
热议问题