Java File Exist fileExists(File file)

Here you can find the source of fileExists(File file)

Description

Determine if a file exists.

License

Open Source License

Parameter

Parameter Description
file a file object. May be null, in which case false is returned.

Return

whether the file exists.

Declaration

public static boolean fileExists(File file) 

Method Source Code


//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;
    }
}

Related

  1. fileExist(String cmdPath)
  2. fileExist(String p_filename)
  3. fileExist(String path)
  4. fileExists(File dir, String regex)
  5. fileExists(File directory, String fileName)
  6. fileExists(File path)
  7. fileExists(final String path)
  8. fileExists(final String path)
  9. fileExists(final String pathname)