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
Popular Posts
1Z0-830 Java SE 21 Developer Certification
Azure AI Foundry Hello World
Azure AI Agent Hello World
Foundry vs Hub Projects
Build Agents with SDK
Bing Web Search Agent
Function Calling Agent
Spring Boot + Azure Key Vault Hello World Example
Spring Boot + Elasticsearch + Azure Key Vault Example
Spring Boot Azure AD (Entra ID) OAuth 2.0 Authentication
Deploy Spring Boot App to Azure App Service
Secure Azure App Service using Azure API Management
Deploy Spring Boot JAR to Azure App Service
Deploy Spring Boot + MySQL to Azure App Service
Spring Boot + Azure Managed Identity Example
Secure Spring Boot Azure Web App with Managed Identity + App Registration
Elasticsearch 8 Security - Integrate Azure AD OIDC