简体   繁体   English

如何验证字符串路径在java类中是否有效

[英]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,我获得了用于从配置文件读取字符串文件路径的系统属性,并在我的 java 类中使用此字符串路径,

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.如果目录可能是自动创建的,请在创建目录时检查file.mkdirs()返回的布尔值。
  • 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.如果您可以使用destination.mkdir()看到,如果不存在,我们会得到一个新文件夹。 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.如果您尝试在具有无效路径的File类中使用toPath()方法,您将收到 InvalidPathException。 You can use it to write a function that tests your String :您可以使用它来编写一个测试您的 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.似乎此代码仅适用于 Windows。 On Linux, the InvalidPathException isn't thrown.在 Linux 上,不会抛出 InvalidPathException。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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