Java File Exists Sample Code

The sample Java code below shows you how to check to see if a file exists already. The Java File Class has a method called exists() that will do exactly as it is named, check for a file. At the same time, I like to make sure the file I am checking is not a directory so I also like to use the method isDirectory() and put a ! in front of it.

Java Class: File
Method Name: exists()
Parameters: none
Return Type: boolean
Exceptions: SecurityException

Java Write File Source Code

package com.jcd.java.tutorials;

import java.io.File;

public class JavaFileExists 
{

	 public static void main( String[] args )
	 {
		//String with path of filename 
		String sampleFile = "C:\\Users\\Admin\\Documents\\JavaFile.txt";
		
		//Create File object using above string
		File file = new File(sampleFile);
			
		System.out.println("Using File.exists() method to check for file existence:");
		
		//Call method that uses File.exists()
		if(checkIfFileExists( file ))
		{
			System.out.println("\nFile Does Exist and Is Not a Directory!");
		}
		else 
		{
			System.out.println("\nFile Does Not Exist or File May Be a Directory!");
		}
		
	}
	 
	public static boolean checkIfFileExists( File file )
	{
		boolean bool = false;
		
		try 
		{
				
			//Use exists() method to see if this is a file
			//Use ! isDirectory() method to make sure not a directory
			if (file.exists() && !file.isDirectory())
			{
				bool = true;
			}
			else
			{
				bool = false;
			}
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}
		
		return bool;
	}

}


Java File Exist Sample Output

Using File.exists() method to check for file existence:

File Does Exist and Is Not a Directory!


Java File NOT Exist Sample Output

Using File.exists() method to check for file existence:

File Does Not Exist or File May Be a Directory!


I would also like to point out that the createNewFile() method of the File class will yield a similar results. If the file doe snot exist and can be created, it will return true. If the file already exists, it will return false.

Sample Code Using File.createNew() Method:

     try 
		{
			File file = new File(sampleFile);
			if(file.createNewFile()) 
			{
				System.out.println("Created new file");
			}
			else
			{
				System.out.println("File Already Exists");
			}
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *