簡體   English   中英

如何驗證字符串路徑在java類中是否有效

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

我獲得了用於從配置文件讀取字符串文件路徑的系統屬性,並在我的 java 類中使用此字符串路徑,

private static final String PROPERTY_FILE_PATH = "com.java.var.file.path";

我的配置文件是這樣的:

filePath="$/varDir/temp/fileName"

我想要做的是確保路徑有效。 我寫了這個,但不知道如何驗證正確的路徑。

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

要執行檢查,您首先需要有一個文件句柄:

File file=new File(filepath);

額外的檢查(取決於你想做什么):

  • 檢查文件是否為目錄
    file.isDirectory()
  • 檢查文件是否存在
    file.exists()
    如果目錄可能是自動創建的,請在創建目錄時檢查file.mkdirs()返回的布爾值。
  • 檢查讀取訪問
    file.canRead()
  • 檢查寫訪問
    file.canWrite()

簡單快捷的方法是:

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

如果您可以使用destination.mkdir()看到,如果不存在,我們會得到一個新文件夾。 因此,如果您要將文件從一個地方復制到另一個地方,如果目標文件夾不存在,那么它將自動創建並且復制過程正常。

如果您嘗試在具有無效路徑的File類中使用toPath()方法,您將收到 InvalidPathException。 您可以使用它來編寫一個測試您的 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
 }

更新

似乎此代碼僅適用於 Windows。 在 Linux 上,不會拋出 InvalidPathException。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM