dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Jun 1, 2021

Java: Checking to See if a File Exists

Sometimes it is necessary to see if a file exists in a given file directory. Java has several methods to handle such a task and we explore one of them today - specifically, Java’s File class, java.io.File, which is Java’s representation of a file or a directory path name.

Java.io.File contains a few methods that developers can use to work with path names, allowing programmers to create new directories, find out attributes of files and directories, list the contents of a directory, delete files, and rename files.

Here is some sample Java code that lets you check if a file exists using javaio.File.

*/

import java.io.File;

public class DoesFileExists 
{ 
	public static void main(String[] args) 
	{
		DoesFileExists doesFileExists = new DoesFileExists();
		doesFileExists.proceed();
	}

	private void proceed()
	{
		String fileToBeChecked = "/opt/java-apps/dir-functions/DoesFileExists.java";
		File file = new File(fileToBeChecked);

		if (file.exists())
		{
			System.out.println("File " + fileToBeChecked + " exists");
		}
		else
		{
			System.out.println("File " + fileToBeChecked + " does not exists");
		}
	} 
} 

/*

The Java code above should create the following output, showing whether or not the searched for file exists:

[root@mypc]# java DoesFileExists
File E:\Sridhar\Tips\2021\5-May\DoesFileExists.java exists
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date