Languages
[Edit]
EN

Java - check if file is directory

0 points
Created by:
kaya31
526

In this article, we would like to show you how to check that file is a directory in Java.

Quick solution:

import java.io.File;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        File file = new File("C:\\projects\\file.txt");

        if (file.isDirectory()) {
            System.out.println("File is a directory.");
        } else {
            System.out.println("File denoted by this pathname not exists or is not a directory.");
        }
    }
}

Another example

import java.io.File;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        File file = new File("C:\\projects\\file.txt");
        System.out.println("File is a directory: " + file.isDirectory()); // File is a directory: false
    }
}

Practical example

Projects structure

 C/
 |
 +- projects/
     |
     +- file.txt

Code:

import java.io.File;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        File file1 = new File("C:\\projects\\file.txt");
        File file2 = new File("C:\\projects");

        System.out.println("File1 is a directory: " + file1.isDirectory());
        System.out.println("File2 is a directory: " + file2.isDirectory());
    }
}

Output:

File1 is a directory: false
File2 is a directory: true
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join