user3409650
user3409650

Reputation: 523

How to validate that the string path is valid in java class

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

Answers (4)

JeyJ
JeyJ

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
 }

Update

It seems this code is working only on Windows. On Linux, the InvalidPathException isn't thrown.

Upvotes: 1

Stefanidis
Stefanidis

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

user2504380
user2504380

Reputation: 545

Guessing what you mean by "valid": new File(filepath).exists()

Upvotes: 0

Peter Walser
Peter Walser

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):

  • Check if the file is a directory:
    file.isDirectory()
  • Check if the file exists:
    file.exists()
    If the directory may be automatically created, check the boolean returned by file.mkdirs() when creating the directory.
  • Check read access:
    file.canRead()
  • Check write access:
    file.canWrite()

Upvotes: 6

Related Questions