Check if Java File Name and Path is valid
-
1. Check if File Exists
We should check if the file to be created exists using file.exists() -
2. Make use of the Java 7 java.nio.file.Paths class.
public static boolean isPathValid(String path) { try { Paths.get(path); } catch (InvalidPathException ex) { return false; } return true; }
The Paths.get(path) method returns a path. However if the path is not valid, then it throws InvalidPathException.
For example Path.get("C://test.txt") will return true while Path.get("C://tes?t.txt") will throw an InvalidPathException. -
3. Make use of the File.getCanonicalPath()
File.getCanonicalPath() will throw IOException if the file path contains invalid filename like "?", "|".public static boolean isValidFilePath(String path) { File f = new File(path); try { f.getCanonicalPath(); return true; } catch (IOException e) { return false; } }
isValidFilePath("C://test.txt") will throw true above while isValidFilePath("C://te?st.txt") will return false.
See Also
Spring Boot Interview Questions Apache Camel Interview Questions Drools Interview Questions Java 8 Interview Questions Enterprise Service Bus- ESB Interview Questions. JBoss Fuse Interview Questions Top ElasticSearch frequently asked interview questions