Java File exists() method with examples

November 29, 2019 No comments Java IO Examples File

1. Introduction

The exists() method tests whether the file or directory with a specified pathname exists in the filesystem.

2. Method signature

public boolean exists()

Parameters:

  • method does not take any parameter

Returns

  • true - if file or directory exists in the filesystem

Throws

  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. Check if file /tmp/frontbackend.txt exists

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f = new File("/tmp/frontbackend.txt");
            boolean exists = f.exists();

            if (exists) {
                System.out.println("File exists");
            } else {
                System.out.println("The file does not exist");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output if file exists:

File exists

3.1. Checking if directory /tmp/frontbackend exists

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f = new File("/tmp/frontbackend");
            boolean exists = f.exists();

            if (exists) {
                System.out.println("Directory exists");
            } else {
                System.out.println("Directory does not exist");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output when the specified directory exists in the filesystem will be:

Directory exists

4. Conclusion

In this article we presented File.exists() the method that was created to check if a specified file or directory exists in the filesystem.

{{ message }}

{{ 'Comments are closed.' | trans }}