How to check if a file exists in java?

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!!!");
        }
    }
}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.