Search code examples
androidandroid-10.0scoped-storage

Should we use getPath or getAbsolutePath in Android


When working with files in Android system, should we use File getPath or getAbsolutePath?

For example we downloaded file, then we use DownloadManager.addCompletedDownload() to add this file to global downloads folder to be available there, which path we should pass?

Another example when we create File inside context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath() folder, getPath or getAbsolutePath?

And last example when we use MediaScannerConnection.scanFile()


Solution

  • On Android, it is a common practice not to rely on System.getProperty("user.dir"). At any rate, when the zigote starts your app, this is set to /, and there is only one filesystem, so for all practical purposes, File.getPath() and File.getAbsolutePath() will produce identical results.

    But if you are going for the style points, you are expected to use absolute paths when your process communicates to other processes, including system services. Therefore talking to DownloadManager or to MediaScanner, you will better express you intent by using getAbsolutePath(). On the other hand, for in-app file paths, e.g. getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) to find and read a file, getPath() will be more appropriate.