How to check if a file exists in java?

DeeKay March 19, 2012 at 1:12 am · java.io

Below Java code shows how to check if a file exists –

/****************************************************************************************
 * Created on 03-2012 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * Created by http://kodehelp.com
 * Date: 3/18/12
 */
public class CheckIfFileExists {
    public static void main(String[] args) throws Exception {

        File file = new File("c:/sample.txt");

        System.out.println("File = " + file.getAbsolutePath());
        if (!file.exists()) {
            System.out.println("Sample.txt file does not exist!!!");
            throw new FileNotFoundException("Sample.txt file does not exist!!!");
        }else{
            System.out.println("Sample.txt file exist!!!");
        }
    }
}