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:
xxxxxxxxxx
1
import java.io.File;
2
import java.io.IOException;
3
4
public class Example {
5
6
public static void main(String[] args) throws IOException {
7
File file = new File("C:\\projects\\file.txt");
8
9
if (file.isDirectory()) {
10
System.out.println("File is a directory.");
11
} else {
12
System.out.println("File denoted by this pathname not exists or is not a directory.");
13
}
14
}
15
}
xxxxxxxxxx
1
import java.io.File;
2
import java.io.IOException;
3
4
public class Example {
5
6
public static void main(String[] args) throws IOException {
7
File file = new File("C:\\projects\\file.txt");
8
System.out.println("File is a directory: " + file.isDirectory()); // File is a directory: false
9
}
10
}
Projects structure
xxxxxxxxxx
1
C/
2
|
3
+- projects/
4
|
5
+- file.txt
Code:
xxxxxxxxxx
1
import java.io.File;
2
import java.io.IOException;
3
4
public class Example {
5
6
public static void main(String[] args) throws IOException {
7
File file1 = new File("C:\\projects\\file.txt");
8
File file2 = new File("C:\\projects");
9
10
System.out.println("File1 is a directory: " + file1.isDirectory());
11
System.out.println("File2 is a directory: " + file2.isDirectory());
12
}
13
}
Output:
xxxxxxxxxx
1
File1 is a directory: false
2
File2 is a directory: true