Search code examples
javaandroidfileandroid-support-librarydocumentfile

Difference between File and DocumentFile in Java


What's exactly the difference between a java.util.File and a android.support.v4.provider.DocumentFile in Java Android?


Solution

  • In short:

    File is the "normal" Java file that one would normally know if even he never touched Android - i.e. abstraction for accessing underlying OS's files/directories.

    DocumentFile was introduced to further abstract this in Android's Storage Access Framework (SAF) - it is either backed by "normal" file or by another abstraction called DocumentProvider https://developer.android.com/guide/topics/providers/document-provider.html and could be used to access both types of files in a more generic way. It is part of Google's continuing effort to 'hide' the underlying OS file/directory structure.

    One approach would be to use both File (when accessing disk/card files) or DocumentFile (when accessing files backed from ContentProvider) but the more "modern" way would be to use always DocumentFile, which can represent a normal File by using fromFile(File)