Check that file exists java

How to check if file exists in Java [Practical Examples]

Java provides extensive support to File Handling. In other words, File handling in Java implies reading from and writing data to a file. The File class from the java.io package, allows us to work with different formats of files. But, before operating on file, we need to check if a file exists or not. There are three possibilities for the file either file exist, or file doesn’t exist or it may be possible that file status is not known.

In Java, there are three different ways to check if a file exists or not. They are as listed below.

  • Using exists method of Legacy I/O File class
  • Using isFile method of File class
  • Using exists method of NIO File class

Method-1: Using exists method of File class

Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks. The exists() is a static method of java.io.File class that tests whether a file exist or not. This is a traditional approach to find if the file exists or not. This method does not accept any parameter. However, it returns a boolean value True or False to indicate if the file exist or not. Moreover, this method will raise a Security Exception if the file does not have a write access.

Читайте также:  Php проверить является ли символ числом

There is one more issue with only using the exists() method to check if a file exists or not. Because, it returns a true value if we accidentally specify a directory. So we have to use the method isDirectory() also to make sure that the given argument is a file but not a directory.

The syntax of exists method is as shown below.

Example : In this example, we will create two objects of file class that points to the file in the local directory. Here, we are using exists method of legacy file I/O class and is directory method to check if the given file is a directory or not.

// Importing File package import java.io.File; public class Main < public static void main(String[] args) < // Initializing string to store the path String s1 = "C:\\sample.txt"; String s2 = "C:\\xyz.txt"; // Creating file handle File f1 = new File(s1); File f2 = new File(s2); // Check if file a exists and is not directory if (f1.exists() & amp; & amp; !f1.isDirectory()) < System.out.println(f1 + " exists in the given directory."); >else < System.out.println(f1 + " does not exists or it may be a directory."); >// Check if a file exists if (f2.exists()) < System.out.println(f2 + " exists in the given directory."); >else < System.out.println(f2 + " does not exists in the given directory."); >> >
C:\sample.txt does not exists or it may be a directory. C:\xyz.txt exists

Method-2: Using isFile method of File class

Prior to the Java SE 7 release, the isFile() is a static method of java.io.File class that tests whether a file exist or not. This is a also widely used approach to find if the file exists or not. This method does not accept any parameter. However, it returns a boolean value True or False to indicate if the file exist or not. Moreover, this method will raise a Security Exception if the file does not have a write access.

Читайте также:  Знакомство с GET-запросами

The advantage of using the isFile() method over the exists() method is that we will not have to check if the given file is a directory or not. Unlike, exists() method this file will not return True for directory.

The syntax of isFile method is as shown below.

// Importing File package import java.io.File; class Main < public static void main(String[] args) < // Storing path as a string String p = "C:\pythondemo\test.txt"; //Creating file object File f = new File(p); // Check if it is a file using isFile method if (f.isFile()) < System.out.println("The file " + p + " exists in the given directory."); >else < System.out.println("Either file " + p + " doesn't exist in the given directory or this program may not have access to the file"); >> >
Either file C:\pythondemo\test.txt doesn't exist in the given directory or this program may not have access to the file.

Method-3: Using NIO

From Java 7 onward, the exists() method of java.nio.file.Files is a static method that returns true if the file exists. Whereas, the notExists() method returns true when it does not exist. Moreover, if both exists() and notExists() return false , the existence of the file cannot be verified. This may happen when the program does not have access to the file. Also the result of this method is immediately outdated. So, if this method indicates the file exists then there is no guarantee that a sub sequence access will succeed. Thus, we must be careful when using this method in security sensitive applications.

Note that Files.exists() returns true when your path points to a directory. So, it is recommended to use this method along with the Files.isDirectory() method, which checks the file for a directory.

The syntax of exists method and notExists method is as shown below.

Files.exists(path, options) Files.notExists(path, options)

The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Example : In this example, we are using get method to obtain a Path to the intended file or directory. Then we can pass that Path to the Files.exists() method.

// Importing File package import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Main < public static void main(String[] args) < Path p = Paths.get("/sample.txt"); // check if a file exists for file and directory if (Files.exists(p)) < // Check if it is a file if (Files.isRegularFile(p)) < System.out.println("File " + p + " exists in this directory!"); >// Check if it is a directory if (Files.isDirectory(p)) < System.out.println("File " + p + " exists in this directory but, it is not a file. It is a directory."); >> else < System.out.println("File " + p + " does not exist in this directory"); >if (Files.notExists(q)) < System.out.println("File " + q + " does not exist in this directory"); >> >
File /sample.txt exists in this directory. File /xyz.txt does not exists in this directory.

Summary

The concept to check if a file exists or not is very useful. In many applications we need to perform some important operations that should not result into exception. So, it is very necessary to check if a file exists or not before proceeding with any other operations. We have covered three different ways to check if a file exists or not in Java with example. All in all, this tutorial, covers everything that you need to know in order to check the existence of file in Java.

Источник

Checking a File or Directory

You have a Path instance representing a file or directory, but does that file exist on the file system? Is it readable? Writable? Executable?

Verifying the Existence of a File or Directory

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists, or does not exist. You can do so with the exists(Path, LinkOption. ) and the notExists(Path, LinkOption. ) methods. Note that !Files.exists(path) is not equivalent to Files.notExists(path) . When you are testing a file’s existence, three results are possible:

  • The file is verified to exist.
  • The file is verified to not exist.
  • The file’s status is unknown. This result can occur when the program does not have access to the file.

If both exists and notExists return false , the existence of the file cannot be verified.

Checking File Accessibility

To verify that the program can access a file as needed, you can use the isReadable(Path) , isWritable(Path) , and isExecutable(Path) methods.

The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.

Path file = . ; boolean isRegularExecutableFile = Files.isRegularFile(file) & Files.isReadable(file) & Files.isExecutable(file);

Note: Once any of these methods completes, there is no guarantee that the file can be accessed. A common security flaw in many applications is to perform a check and then access the file. For more information, use your favorite search engine to look up TOCTTOU (pronounced TOCK-too).

Checking Whether Two Paths Locate the Same File

When you have a file system that uses symbolic links, it is possible to have two different paths that locate the same file. The isSameFile(Path, Path) method compares two paths to determine if they locate the same file on the file system. For example:

Path p1 = . ; Path p2 = . ; if (Files.isSameFile(p1, p2)) < // Logic when the paths locate the same file >

Источник

Check If a File or Directory Exists in Java

Learn to test if a file or a directory exists in a given path using Java standard IO and NIO APIs.

1. Using Files.exists() and Files.notExists()

Java NIO provides a few good ways to test whether the specified file or directory exists or not. Use Files.exists() method or Files.notExists() method for such validations.

Path path = Files.createTempFile("testFile", ".txt"); boolean exists = Files.exists(path); //true //OR Path tempDirectory = Files.createTempDirectory("temp-dir"); boolean exists = Files.notExists(tempDirectory); //false

By default, this method follows the symbolic links. Use the LinkOption#NOFOLLOW_LINKS if symbolic links are not to be followed.

Files.exists(symbolicLinkToFile, LinkOption.NOFOLLOW_LINKS)

2. Using Legacy File.exists()

To test to see if a file or directory exists, use the “ exists() ” method of the Java java.io.File class.

  • If the exists() method returns true then the file or directory does exist and otherwise does not exists.
  • If there is a read permission issue then it will throw SecurityException.
File tempFile = new File("c:/temp/temp.txt"); boolean exists = tempFile.exists();

3. Checking if File is Readable, Writable or Executable

To verify that the program can access a file as needed, you can use the isReadable(Path), isWritable(Path), and isExecutable(Path) methods.

Java program to test a file if it is readable, writable and executable. You can need to build Path instances as discussed in the linked post.

final Path path = . ; Files.isReadable(path); //OR Files.isWritable(path); //OR Files.isExecutable(path);

That’s all for a quick tip related to checking if a file or directory exists or does not exists in java. Along with testing if the program is allowed to append content to it by checking its writable attribute.

Источник

Оцените статью