Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in Java to determine if a path is valid without attempting to create a file?

I need to determine if a user-supplied string is a valid file path (i.e., if createNewFile() will succeed or throw an Exception) but I don't want to bloat the file system with useless files, created just for validation purposes.

Is there a way to determine if the string I have is a valid file path without attempting to create the file?

I know the definition of "valid file path" varies depending on the OS, but I was wondering if there was any quick way of accepting C:/foo or /foo and rejecting banana.

A possible approach may be attempting to create the file and eventually deleting it if the creation succeeded, but I hope there is a more elegant way of achieving the same result.

like image 519
Raibaz Avatar asked Jan 22 '09 11:01

Raibaz


People also ask

How do I check if Java path is correct?

Open a Command Prompt window (Win⊞ + R, type cmd, hit Enter). Enter the command echo %JAVA_HOME% . This should output the path to your Java installation folder. If it doesn't, your JAVA_HOME variable was not set correctly.

How do you check if file path does not exist in Java?

However, to make sure if a file or directory exists in Java legacy IO world, we can call the exists() method on File instances: assertFalse(new File("invalid").

How do you check if a path is a directory Java?

io. File. isDirectory() checks whether a file with the specified abstract path name is a directory or not. This method returns true if the file specified by the abstract path name is a directory and false otherwise.


2 Answers

Path class introduced in Java 7 adds new alternatives, like the following:

/**
 * <pre>
 * Checks if a string is a valid path.
 * Null safe.
 *  
 * Calling examples:
 *    isValidPath("c:/test");      //returns true
 *    isValidPath("c:/te:t");      //returns false
 *    isValidPath("c:/te?t");      //returns false
 *    isValidPath("c/te*t");       //returns false
 *    isValidPath("good.txt");     //returns true
 *    isValidPath("not|good.txt"); //returns false
 *    isValidPath("not:good.txt"); //returns false
 * </pre>
 */
public static boolean isValidPath(String path) {
    try {
        Paths.get(path);
    } catch (InvalidPathException | NullPointerException ex) {
        return false;
    }
    return true;
}

Edit:
Note Ferrybig's comment : "The only disallowed character in a file name on Linux is the NUL character, this does work under Linux."

like image 73
c0der Avatar answered Oct 06 '22 17:10

c0der


This would check for the existance of the directory as well.

File file = new File("c:\\cygwin\\cygwin.bat");
if (!file.isDirectory())
   file = file.getParentFile();
if (file.exists()){
    ...
}

It seems like file.canWrite() does not give you a clear indication if you have permissions to write to the directory.

like image 42
krosenvold Avatar answered Oct 06 '22 17:10

krosenvold