Reputation: 523
I get system property for reading a string file path from a config file and I use this string path in my java class,
private static final String PROPERTY_FILE_PATH = "com.java.var.file.path";
and my config file is like this:
filePath="$/varDir/temp/fileName"
what I want to do is to make sure that the path is valid. I wrote this but do not know how to validate the correct path.
if (PROPERTY_FILE_PATH == null || PROPERTY_FILE_PATH.trim().isEmpty()) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("The path for keystore file is blank. Please provide a valid path for the file.");
}
return;
}
Upvotes: 1
Views: 9268
Reputation: 4070
If you will try to use the toPath()
method in the File
class with an invalid path you will get an InvalidPathException. You can use it to write a function that tests your String :
public boolean isPathValid(String path){
if (path == null)
return false;
try {
Path path = new File(path).toPath();
return true;
}
catch (InvalidPathException exceptio){
return false
}
It seems this code is working only on Windows. On Linux, the InvalidPathException isn't thrown.
Upvotes: 1
Reputation: 61
The simple and fast way is:
public boolean isValidFile(File destination) throws IOException {
//if given file is null return false
if (destination != null) {
try {
//now we check if given file is valid file (file or folder)
// else we check if we can make a directory with path of given file.
//Thus we validate that is a valid path.
if (destination.isFile() || destination.isDirectory()) {
return true;
//after the following step a new file will be created if it return true, so it is a valid file path.
} else if (destination.mkdir()) {
return true;
}
} catch (Exception e) {
Logger.getLogger(Copy.class.getName()).log(Level.SEVERE, null, e);
}
}
return false;
}
If you can see with destination.mkdir()
we get a new folder if not exists. So if you are going to copy files from one place to another if destination folder does not exist then it will be created auto and copy process works fine.
Upvotes: 1
Reputation: 15706
To perform the checks, you need to have a file handle first:
File file=new File(filepath);
Additional checks (depending on what you want to do):
file.isDirectory()
file.exists()
file.mkdirs()
when creating the directory.file.canRead()
file.canWrite()
Upvotes: 6