EN
Java - check if file exists
0 points
In this article, we would like to show you how to check that file is exists using Java.
Quick solution:
xxxxxxxxxx
1
import java.io.File;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
File file = new File("C:\\projects\\file.txt");
7
8
if (file.exists()) {
9
System.out.println("File exists.");
10
} else {
11
System.out.println("File does not exists.");
12
}
13
}
14
}
xxxxxxxxxx
1
import java.io.File;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
File file = new File("C:\\projects\\file.txt");
7
System.out.println("Is file exists: " + file.exists());
8
}
9
}
Projects structure
xxxxxxxxxx
1
C/
2
|
3
+- projects/
4
|
5
+- file.txt
Code
xxxxxxxxxx
1
import java.io.File;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
File file = new File("C:\\projects\\file.txt");
7
File anotherFile = new File("C:\\projects\\anotherFile.txt");
8
9
System.out.println("Is file.txt exists: " + file.isFile());
10
System.out.println("Is anotherFile.txt exists: " + anotherFile.isFile());
11
}
12
}
Output:
xxxxxxxxxx
1
Is file.txt exists: true
2
Is anotherFile.txt exists: false