Is There a Way in Java to Determine If a Path Is Valid Without Attempting to Create a File

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

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.

How to check whether a (String) location is a valid saving path in Java?

You can use File.getCanonicalPath() to validate according the current OS rules.

import java.io.File;
import java.io.IOException;

public class FileUtils {
public static boolean isFilenameValid(String file) {
File f = new File(file);
try {
f.getCanonicalPath();
return true;
}
catch (IOException e) {
return false;
}
}

public static void main(String args[]) throws Exception {
// true
System.out.println(FileUtils.isFilenameValid("well.txt"));
System.out.println(FileUtils.isFilenameValid("well well.txt"));
System.out.println(FileUtils.isFilenameValid(""));

//false
System.out.println(FileUtils.isFilenameValid("test.T*T"));
System.out.println(FileUtils.isFilenameValid("test|.TXT"));
System.out.println(FileUtils.isFilenameValid("te?st.TXT"));
System.out.println(FileUtils.isFilenameValid("con.TXT")); // windows
System.out.println(FileUtils.isFilenameValid("prn.TXT")); // windows
}
}

Check if a path represents a file or a folder

Assuming path is your String.

File file = new File(path);

boolean exists = file.exists(); // Check if the file exists
boolean isDirectory = file.isDirectory(); // Check if it's a directory
boolean isFile = file.isFile(); // Check if it's a regular file

See File Javadoc


Or you can use the NIO class Files and check things like this:

Path file = new File(path).toPath();

boolean exists = Files.exists(file); // Check if the file exists
boolean isDirectory = Files.isDirectory(file); // Check if it's a directory
boolean isFile = Files.isRegularFile(file); // Check if it's a regular file


Related Topics



Leave a reply



Submit