How to check if a file exists in Java

It is very easy to check if file exists or not in your file system. You can use java.io.File's exists() method to check if file exists or not.

Java program :

package org.arpit.java2blog;

import java.io.File;

public class FileExistsMain {
 /*
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {

  System.out.println("-----------------");
  // Read the file
  File mp3File=new File("/Users/Arpit/Desktop/MySong.mp3");
  
  if(mp3File.exists())
  {
   System.out.println("MySong.mp3 file exists");
  }
  else
  {
   System.out.println("MySong.mp3 file does not exist");
  }
  
  System.out.println("-----------------");
  
  File mp3FileFolder=new File("/Users/Arpit/Desktop/MySong");
  
  if(mp3FileFolder.exists())
  {
   System.out.println("MySong folder exists");
  }
  else
  {
   System.out.println("MySong folder does not exist");
  }
  System.out.println("-----------------");
 }

}

When you run above program, you will get following output:
-----------------
MySong.mp3 file exists
-----------------
MySong folder does not exist
-----------------

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012