簡體   English   中英

驗證字符串輸入可以是有效路徑

[英]Validate String input COULD be a valid path

我希望驗證一個字符串路徑。 我不想檢查路徑是否存在或創建路徑(包括create + then delete),我只想檢查輸入字符串COULD是執行系統上的驗證路徑。

到目前為止,我一直在搞亂File類,沒有運氣。 我希望我的OSX機器上的以下內容失敗,但它沒有:

File f = new File("!@£$%^&*()±§-_=+[{}]:;\"'|>.?/<,~`±");
System.out.println(f.getCanonicalPath());

有什么能幫我的嗎?

你可以通過正則表達式來實現: javascript中的文件路徑驗證

或者通過檢查路徑的父節點是否存在: Java中是否有辦法確定路徑是否有效而不嘗試創建文件?

請注意,路徑取決於操作系統: https//serverfault.com/questions/150740/linux-windows-unix-file-names-which-characters-are-allowed-which-are-unesc

另外,僅僅因為路徑有效,並不意味着可以在那里寫入文件。 例如,在Linux中,您需要成為超級用戶才能寫入/ usr /

您可以選擇使用正則表達式來檢查路徑。 正則表達式看起來像:

^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$

Regexr就是一個例子。 您可以使用String.matches(regex)函數在Java進行檢查。 以下示例:

public static void main(String[] args) throws Exception {

    String regex = "^(?:[a-zA-Z]\\:|\\\\\\\\[\\w\\.]+\\\\[\\w.$]+)\\\\(?:[\\w]+\\\\)*\\w([\\w.])+$";
    String path = "c:\\folder\\myfile.txt";

    System.out.println(path.matches(regex));

}

請注意,由於必須轉義\\字符,正則表達式看起來要長得多 )。 只需調用yourPathString.matches(regex) ,如果它是有效路徑,它將返回true。

如果路徑有效,則必須至少存在一個父文件鏈。 如果不存在父級,則它必須無效。

public static boolean isValidPath(File file) throws IOException {
    file = file.getCanonicalFile();

    while (file != null) {
        if (file.exists()) {
            return true;
        }

        file = file.getParentFile();
    }

    return false;
}

System.out.println(isValidPath(new File("/Users/something")));  // true (OS X)
System.out.println(isValidPath(new File("asfq34fawrf")));  // false

暫無
暫無

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

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