How to check if a file exists in java?

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

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

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

/**
* Created by https://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!!!");
}
}
}
[/java]

Please Post Your Comments & Reviews

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