
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a File Exists in Java
The java.io.File class provides useful methods on file. This example shows how to check a file existence by using the file.exists() method of File class.
Example
import java.io.File; public class Main { public static void main(String[] args) { File file = new File("C:/java.txt"); System.out.println(file.exists()); } }
Result
The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).
true
Example
The following is another simple example of the file exist or not in java.
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintpWriter; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class fileexist { public static void main(String[] args) throws IOException { File f = new File(System.getProperty("user.dir")+"/folder/file.txt"); System.out.println(f.exists()); if(!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } if(!f.exists()) { try { f.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } try { File dir = new File(f.getParentFile(), f.getName()); PrintpWriter pWriter = new PrintpWriter(dir); pWriter.print("writing anything..."); pWriter.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
Output
The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).
true
Advertisements