Check if a file exists in Java

Object Oriented ProgrammingJava Programming Java8

The java.io.File class provides useful methods on file. This example shows how to check a file existence by using the file.exists() method of File class.

Example

import java.io.File;

public class Main {
   public static void main(String[] args) {
      File file = new File("C:/java.txt");
      System.out.println(file.exists());
   }
}

Result

The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).

true

Example

The following is another simple example of the file exist or not in java.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintpWriter;

import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class fileexist {
   public static void main(String[] args) throws IOException {
      File f = new File(System.getProperty("user.dir")+"/folder/file.txt");
      System.out.println(f.exists());

      if(!f.getParentFile().exists()) {
          f.getParentFile().mkdirs();
      }        

      if(!f.exists()) {
         try {
            f.createNewFile();
         } catch (Exception e) {
            e.printStackTrace();
         }        
      }

      try {
         File dir = new File(f.getParentFile(), f.getName());
         PrintpWriter pWriter = new PrintpWriter(dir);
         pWriter.print("writing anything...");
         pWriter.close();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      }    
   }
}

Output

The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).

true
raja
Published on 20-Jul-2018 13:49:27
Advertisements