Languages
[Edit]
EN

Java - check if file is regular file

0 points
Created by:
Burhan-Boyce
458

In this article, we would like to show you how to check if the file is a regular file 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.isFile()) {
            System.out.println("File is a regular file.");
        } else {
            System.out.println("File denoted by this pathname not exists or is not a regular file.");
        }
    }
}

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 regular file: " + file.isFile());
    }
}

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 regular file: " + file1.isFile());
        System.out.println("File2 is a regular file: " + file2.isFile());
    }
}

Output:

File1 is a regular file: true
File2 is a regular file: false
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 IO Tutorial

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