EN
Java - check if file is directory
0
points
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