

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Check if a File exists in C#
- How to check if a file exists or not in Java?
- How to check if a file exists in Golang?
- Determine if file or directory exists in Java
- How to check if a file exists or not using Python?
- How to use Lua Programming to check if a file exists?
- Check if a particular key exists in Java LinkedHashMap
- Check if a particular value exists in Java LinkedHashMap
- Check if a given key exists in Java HashMap
- Check if a particular value exists in Java TreeSet
- Check if a particular element exists in Java LinkedHashSet
- How can we check if file exists anywhere on the system in Java?
- Java Program to check whether a file exists or not
- Check if a file is hidden in Java
- Check if MongoDB database exists?
Advertisements