How to check if a file exists in Java

To determine whether a file is exist in your file system, use the Java IO File.exists().


package com.mkyong.io;

import java.io.*;

public class FileChecker {
	
  public static void main(String args[]) {
    
	  File f = new File("c:\\mkyong.txt");

	  if(f.exists()){
		  System.out.println("File existed");
	  }else{
		  System.out.println("File not found!");
	  }
      
  }
  
}

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
12 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
12 Comment authors
sai priyaRamya YALI AKHTARLijo JoseArcosBinary Recent comment authors
newest oldest most voted
sai priya
Guest
sai priya

How to load a file dynamically without giving i’ts path? Can you please share the sample code

Ramya Y
Guest
Ramya Y

i need to delete a record from text file in java

ALI AKHTAR
Guest
ALI AKHTAR

In my C folder I made a file called ali.txt.

File f = new File(“c:\ali.txt”);
if(f.exists()){
System.out.println(“File existed”);
}else{
System.out.println(“File not found!”);
}

But it gives me File not found.

Lijo Jose
Guest
Lijo Jose

Can anyone help me to write a code for finding whether a new image file is added to a specified folder. And if a new file is found execute an action in java

ArcosBinary
Guest
ArcosBinary

@Rajeev You are wrong. After File file = new File(PATH); the file is not yet written to the filesystem.

Ravi
Guest
Ravi

Hi mkyong is it possible to determine whether a file is exist in different server file system

Sanjay.bhodu
Guest
Sanjay.bhodu

@mkyong Thanks for the good work! :)

Rajeev
Guest
Rajeev

Here is the right solution:
if (new File(“/Path/To/File/YourFileName.txt”).exists()){

}

If you are doing …
File f = new File(“c:\\mkyong.txt”);
and then checking the existence, it will always returns true because you are checking the existence after creating the file.

Dan
Guest
Dan

@Piyush – If the file is remote you wouldn’t be telling the program to look for the file in the root of C:

Raymond
Guest
Raymond

This wont always work. f.exist also returns true when it’s a directory

Piyush
Guest
Piyush

What if the file is remote? The above code snippet may fail

Christian
Guest
Christian

You just saved me a headache!!