This quick code tip shows how to check whether a file exists in Java. The Java code example used in the tutorial uses the NIO API’s java.nio.file.Path
and java.nio.file.Files
classes to determine whether a file at the given path in the file system exists or not.
Java NIO-based code example to check for existence of a file
package com.javabrahman.corejava; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileExists { public static void main(String args[]){ //Example of file which doesn't exist Path filePath_1= Paths.get("C:\\xyz.txt"); boolean fileExists_1= Files.exists(filePath_1); System.out.println("File 'xyz.txt' exists: "+fileExists_1); //Example of file which exists Path filePath_2= Paths.get("C:\\JavaBrahman\\LEVEL1\\file1.txt"); boolean fileExists_2= Files.exists(filePath_2); System.out.println("File ‘file1.txt’ exists: "+fileExists_2); } }
File ‘xyz.txt’ exists: false
File ‘file1.txt’ exists: true
File ‘file1.txt’ exists: true
- The above class
FileExists
checks for existence of 2 files –xyz.txt
(which doesn’t exist) andfile1.txt
(which exists)
at their respective paths mentioned in the code. - The check for file existence is done in 2 steps(which need to be repeated for each file check). These steps are –
- Create an instance of
Path
usingPaths.get()
method with the complete file path passed as aString
to it. - Use
Files.exist()
method with thePath
instance variable created in step 1 passed to it as parameter.Files.exist()
returns a boolean value indicating the existence of the file –true
if the file exists andfalse
if it doesn’t.
- Create an instance of
- In the above example, the output is as expected – check for
xyz.txt
returnsfalse
as the file does not exist, while the returned value istrue
forfile1.txt
as it exists at the given file path.
