简体   繁体   中英

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;
        }

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

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.

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.

猜猜“有效”是什么意思: new File(filepath).exists()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM