Android
File Existence Check
Check Without Creation
Android Development
Java File Handling

Android; Check if file exists without creating a new one

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

A common task in Android development is checking whether a file exists before reading from it or writing to it. The important nuance is doing this without accidentally creating the file in the process. Several Android and Java APIs create files as a side effect, so choosing the right approach matters. This article covers the correct techniques for checking file existence on Android, along with permission considerations and common mistakes.

Using java.io.File.exists()

The simplest and most widely used approach is the exists() method from the java.io.File class. This method returns true if the file or directory at the given path exists, and false otherwise. Crucially, it never creates the file.

java
1import java.io.File;
2
3File file = new File("/data/data/com.example.app/files/config.json");
4
5if (file.exists()) {
6    // File is present, safe to read
7    Log.d("FileCheck", "File found");
8} else {
9    // File does not exist
10    Log.d("FileCheck", "File not found");
11}

This approach works for both internal storage and external storage paths. The File constructor only builds a path object in memory. It does not touch the filesystem until you call a method like createNewFile(), so the existence check is completely safe.

Checking Files in Internal Storage

Android provides getFilesDir() and getCacheDir() to get paths within your app's private internal storage. You do not need any special permissions to access these directories.

java
1File internalFile = new File(context.getFilesDir(), "user_preferences.json");
2
3if (internalFile.exists()) {
4    // Read the file
5} else {
6    // Create or download the file
7}

For cache files, swap in getCacheDir().

java
File cacheFile = new File(context.getCacheDir(), "temp_image.png");
boolean cacheExists = cacheFile.exists();

Checking Files in External Storage

External storage requires more care because of Android's permission model. On Android 6.0 (API 23) and above, you must request READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE at runtime before accessing shared external storage.

java
1File externalFile = new File(
2    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
3    "report.pdf"
4);
5
6if (externalFile.exists()) {
7    Log.d("FileCheck", "Report found in Downloads");
8}

On Android 10 (API 29) and above, scoped storage limits direct file path access to shared directories. For broader file access on newer versions, use the Storage Access Framework or the MediaStore API instead.

Using Kotlin's Extension Functions

If you are writing in Kotlin, the same File.exists() method works, and you can take advantage of Kotlin's concise syntax.

kotlin
1val file = File(context.filesDir, "settings.json")
2
3if (file.exists()) {
4    val content = file.readText()
5    // Use the content
6} else {
7    // Handle missing file
8}

Kotlin also provides file.isFile (true only for regular files, not directories) and file.isDirectory for more specific checks.

Methods That Accidentally Create Files

Several APIs create a file as a side effect. Avoid these when you only want to check existence.

FileOutputStream constructor. Opening a FileOutputStream creates the file if it does not exist.

java
// This CREATES the file. Do not use for existence checks.
FileOutputStream fos = new FileOutputStream("data.txt");

File.createNewFile(). This method explicitly creates an empty file. It returns true if the file was created and false if it already existed, but calling it just to check existence leaves behind an empty file when the file was absent.

java
// Do not use this as an existence check
File file = new File(context.getFilesDir(), "data.txt");
boolean existed = !file.createNewFile(); // Side effect: creates file if missing

context.openFileOutput(). This Android-specific method opens (and creates) a file in internal storage. It is designed for writing, not for checking existence.

Common Pitfalls

Forgetting runtime permissions. On API 23 and above, calling exists() on external storage without the proper runtime permission will return false even if the file is there. Always check and request permissions before accessing external paths.

Race conditions. Checking exists() and then reading the file in two separate steps introduces a small window where another process could delete the file. In critical scenarios, wrap the read in a try-catch for FileNotFoundException instead of relying solely on the existence check.

Confusing file and directory. exists() returns true for both files and directories. If you need to confirm the path is specifically a regular file, use isFile() instead.

java
1File path = new File(context.getFilesDir(), "data");
2if (path.isFile()) {
3    // Definitely a file, not a directory
4}

Hardcoding paths. Avoid hardcoding storage paths like /sdcard/. These paths vary across manufacturers and Android versions. Always use getFilesDir(), getExternalFilesDir(), or Environment.getExternalStoragePublicDirectory() to build paths dynamically.

Summary

To check whether a file exists on Android without creating it, use java.io.File.exists(). This method is safe, performs no filesystem modifications, and works for both internal and external storage. For internal storage, combine it with context.getFilesDir() or context.getCacheDir(). For external storage, ensure you have the correct runtime permissions first. Avoid FileOutputStream, createNewFile(), and openFileOutput() when you only want to verify existence, since all three create the file as a side effect.


Course illustration
Course illustration

All Rights Reserved.