title: How to load Tensorflow model from internal storage?
body: <p>I wanted to know if it's possible to store and read the trained .tflite model from the Android device's internal storage instead of the assets folder?</p>
  
  <p>Below is the original code (which works) for loading the model from the assets folder.</p>
  
  <pre><code>private MappedByteBuffer loadLocalModelFile() throws IOException {
    AssetFileDescriptor fileDescriptor = getAssets().openFd(MODEL_PATH);
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
  
    FileChannel fileChannel = inputStream.getChannel();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
  }
  </code></pre>
  
  <p>Is there a way to load the model from internal memory instead and still get the startOffset and declaredLength for fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)? If not, is there a way to calculate the startOffset of a new model and its declared length when reading the raw binary from internal storage?</p>
  
  <p>I tried using the openNonAssetFd() function from AssetManager to obtain an AssetFileDescriptor for my file located in internal storage.</p>
  
  <pre><code>private MappedByteBuffer loadOnlineModelFile() throws IOException {
      FileInputStream inputStream = openFileInput(MODEL);
  
      AssetManager manager = getAssets();
      AssetFileDescriptor afd = manager.openNonAssetFd(getFilesDir() + "/graph.lite");
  
      long startOffset = afd.getStartOffset();
      long declaredLength = afd.getDeclaredLength();
  
      FileChannel fileChannel = inputStream.getChannel();
      return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
    }
  </code></pre>
  
  <p>However, this will result in "java.lang.IllegalArgumentException: Model ByteBuffer should be either a MappedByteBuffer of the model file or a direct ByteBuffer using ByteOrder.nativeOrder() which contains bytes of model content" and "java.io.FileNotFoundException".</p>