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!");
	  }
      
  }
  
}
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. Read all published posts by

Comments

avatar
newest oldest most voted
Christian
Guest
Christian

You just saved me a headache!!

Piyush
Guest
Piyush

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

Raymond
Guest
Raymond

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

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:

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.

Sanjay.bhodu
Guest
Sanjay.bhodu

@mkyong Thanks for the good work! 🙂

Ravi
Guest
Ravi

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

ArcosBinary
Guest
ArcosBinary

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

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

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.

Ramya Y
Guest
Ramya Y

i need to delete a record from text file in java

sai priya
Guest
sai priya

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

Dilip
Guest
Dilip

How to check got multiple files exists in directory.?

Dilip
Guest
Dilip

How to validate for multiple files exists in directory?