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
What Are Good Installanywhere Replacements for Installing a Java Ee Application
Spring Autowiring Class VS. Interface
Java Singleton and Synchronization
JPA Onetomany Not Deleting Child
How to Tune Tomcat 5.5 Jvm Memory Settings Without Using the Configuration Program
Implement Converters for Entities with Java Generics
How to Fix "The Expression of Type List Needs Unchecked Conversion...'
Are Java Primitive Ints Atomic by Design or by Accident
How to Define Multiple Jbutton Actions from a Different Class
Convert a String of Hex into Ascii in Java
How to Set Working Directory with Processbuilder