Here you can find the source of fileExists(File file)
Parameter | Description |
---|---|
file | a file object. May be null, in which case false is returned. |
public static boolean fileExists(File file)
//package com.java2s; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class Main { /**/*from w w w . j av a2s . com*/ * Determine if a file exists. * Workaround for java.io.File lack of support for path names > 260 chars in Windows. * * Note: Creation of the following will correctly throw a FileNotFoundException: * - FileInputStream * - FileReader * - RandomAccessFile * * if the file truly does not exist. * * @param file a file object. May be null, in which case false is returned. * @return whether the file exists. */ public static boolean fileExists(File file) { /* * TODOEL: Only works for files. Doesn't work with folders. * For folders: File.canRead() or create a URL and try to read it? */ if (file == null) { return false; } // We can just use the file.exists() method if the path name isn't too long. if (file.getAbsolutePath().length() < 255) { return file.exists(); } // As far as I can tell, there are two ways to tell if a file with a too-long pathname exists. // 1) Create a FileInputStream, and see if it causes an exception. // 2) Create a RandomAccessFile, and see if it causes an exception. // Testing shows that, at the moment, 2) is faster. RandomAccessFile raFile = null; try { raFile = new RandomAccessFile(file, "r"); return true; } catch (FileNotFoundException e) { } finally { if (raFile != null) { try { raFile.close(); } catch (IOException ioe) { } } } return false; } }