Java File Exist fileExist(String path)

Here you can find the source of fileExist(String path)

Description

Checks that the file at the specified path exists.

License

Open Source License

Parameter

Parameter Description
path the file path to check.

Return

true if the file exists.

Declaration

public static boolean fileExist(String path) 

Method Source Code

//package com.java2s;
/**/*from   w w  w . ja  v  a2  s  . com*/
 *
 * This file is part of Stuffed.
 *
 * Stuffed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Stuffed is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Stuffed.  If not, see <http://www.gnu.org/licenses/>.
 *
 * File name:    Common.java
 * Package: cs.man.ac.uk.common
 * Created:   May 1, 2013
 * Author:   Rob Lyon
 * 
 * Contact:   rob@scienceguyrob.com or robert.lyon@postgrad.manchester.ac.uk
 * Web:      <http://www.scienceguyrob.com> or <http://www.cs.manchester.ac.uk> 
 *          or <http://www.jb.man.ac.uk>
 */

import java.io.File;

import java.io.IOException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**
     * Checks that the file at the specified path exists.
     * @param path the file path to check.
     * @return true if the file exists.
     */
    public static boolean fileExist(String path) {
        if (isPathValid(path)) {
            File f = new File(path);

            try {
                if (!f.getCanonicalPath().equals(path))
                    return false;

                if (f.exists() && !dirExist(path)) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                return false;
            }
        } else
            return false;
    }

    /**
     * Tests whether a path is valid.
     * @param path the path to check.
     * @return true if the file name is valid, else false.
     */
    public static boolean isPathValid(String path) {
        File f;

        if (path != null)
            f = new File(path);
        else
            return false;
        try {
            @SuppressWarnings("unused")
            String canonicalPath = f.getCanonicalPath();

            // Check for invalid characters
            if (isWindows()) {
                return isValidWinPath(path);
            } else if (isMac()) {
                return isValidUnixPath(path);
            } else if (isUnix()) {
                return isValidUnixPath(path);
            } else
                return true;

        } catch (IOException e) {
            return false;
        }
    }

    /**
     * Checks that the directory at the specified path exists.
     * @param path the path to check.
     * @return true if the directory exists
     */
    public static boolean dirExist(String path) {
        if (isPathValid(path)) {
            File dir = new File(path);

            try {
                if (!dir.getCanonicalPath().equals(path))
                    return false;

                if (dir.exists() && dir.isDirectory()) {
                    return true;
                } else {
                    return false;
                }
            } catch (IOException e) {
                return false;
            }
        } else
            return false;
    }

    /**
     * Tests to see if the application is running on windows.
     * @return true if the application is running under windows, else false.
     */
    public static boolean isWindows() {
        String os = System.getProperty("os.name").toLowerCase();
        //windows
        return (os.indexOf("win") >= 0);
    }

    /**
     * Tests to see if a path is valid for the Windows OS.
     * @param path the path to test.
     * @return true if a valid windows path, else false.
     */
    public static boolean isValidWinPath(String path) {
        // If user inputs only a drive letter.
        if (path.length() == 3) {
            return false;
        } else if (path.endsWith("\\")) {
            return false;
        } else {
            String regex = "([a-z]:\\\\(?:[-\\w\\.\\d]+\\\\)*(?:[-\\w\\.\\d]+)?)";

            Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            Matcher m = p.matcher(path);

            // Invalid path characters to explicitly check for.
            String[] invalidChars = { "\"", "/", "*", "?", "<", ">", "|" };

            for (int i = 0; i < invalidChars.length; i++) {
                if (path.contains(invalidChars[i]))
                    return false;
            }

            // Check the only colon appears at start of path, i.e. C:\
            if (path.indexOf(":") > 1)
                return false;

            return (m.find());
        }
    }

    /**
     * Tests to see if the application is running on MacIntosh.
     * @return true if the application is running under MacIntosh, else false.
     */
    public static boolean isMac() {
        String os = System.getProperty("os.name").toLowerCase();
        return (os.indexOf("mac") >= 0);
    }

    /**
     * UNTESTED.
     * Tests to see if a path is valid for the Unix/Linux OS.
     * @param path the path to test.
     * @return true if a valid unix path, else false.
     */
    public static boolean isValidUnixPath(String path) {
        String regex = "((?:\\/[\\w\\.\\-]+)+)";

        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher m = p.matcher(path);
        return m.find();
    }

    /**
     * Tests to see if the application is running on Linux/Unix.
     * @return true if the application is running under Linux/Unix, else false.
     */
    public static boolean isUnix() {
        String os = System.getProperty("os.name").toLowerCase();
        return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);
    }

    /**
     * Checks that the object at the specified path is a directory.
     * @param path the path to check.
     * @return true if the object is a directory.
     */
    public static boolean isDirectory(String path) {
        if (isPathValid(path)) {
            File dir = new File(path);
            if (dir.isDirectory()) {
                return true;
            } else {
                return false;
            }
        } else
            return false;
    }

    /**
     * Checks that the object at the specified path is a directory.
     * @param dir the directory to check.
     * @return true if the object is a directory.
     */
    public static boolean isDirectory(File dir) {
        if (dir.isDirectory()) {
            return true;
        } else {
            return false;
        }
    }
}

Related

  1. doesExist(String fname)
  2. doesExistsInside(File src, String fileName)
  3. fileExist(String _FileName, String _Path)
  4. fileExist(String cmdPath)
  5. fileExist(String p_filename)
  6. fileExists(File dir, String regex)
  7. fileExists(File directory, String fileName)
  8. fileExists(File file)
  9. fileExists(File path)