2013-04-21 30 views
0

注意:無效的問題是由父函數中錯誤放置的!造成的。這個問題被標記出來,以便主持人可以刪除它。如果目錄以點開頭,則File.getCanonicalPath()返回錯誤


我創建了一個函數,檢查(文件/目錄)路徑是否有效,而不檢查它是否存在;

public static boolean isValidPath(String path) { 
    File f = new File(path); 
    try { 
     f.getCanonicalPath(); 
     return true; 
    } catch (IOException e) { 
     return false; 
    } 
} 

的問題是,當File.getCanonicalPath();任何的目錄以點開始返回一個錯誤,altough它是一個用於Windows的有效目錄路徑。這會導致函數返回false,這應該是true。 例如,路徑C:\Users\Tim\AppData\Roaming\.minecraft\bin返回falseC:\Users\Tim\AppData\Roaming\minecraft\bin沒有在我的世界目錄上的點返回true。目錄名中帶有點的第一個路徑確實存在於我的系統中,而且我正在運行Windows 7 64位。是否有其他功能來檢查路徑是否有效,或者我可以採取哪些措施來解決此問題?

+0

你看到什麼樣的錯誤?你能發送堆棧跟蹤嗎? – AlexR 2013-04-21 14:10:06

+0

如果'path'是'C:\ Users \ Tim \ AppData \ Roaming \ minecraft \ bin',那麼'f.getCanonicalPath()'工作正常嗎? – clav 2013-04-21 14:15:07

+0

*「提前致謝, TimVisée」*不要在問題中包含噪音。我的結果似乎與你的陳述相矛盾。爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2013-04-21 14:16:22

回答

1
import java.io.*; 

class TestDirWithDot { 

    public static boolean isValidPath(String path) { 
     File f = new File(path); 
     try { 
      f.getCanonicalPath(); 
      return true; 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return false; 
     } 
    } 

    public static void main(String[] arg) { 
     System.out.println(System.getProperty("os.name")); 
     String path = ".dir"; 
     System.out.println(isValidPath(path)); 
    } 
} 

Windows Vista 
true 
+1

在「Mac OS X」上也一樣。 – trashgod 2013-04-24 03:30:47

+1

在'Linux'(Ubuntu 12.04,OpenJDK)上也是如此。 – trashgod 2013-04-24 03:39:37

0

與目錄名點的第一路徑不我 系統上不存在,我運行Windows 7 64位。

所以你會得到

IOException - 如果發生I/O錯誤,這是可能的,因爲規範路徑名的建設可能需要的文件系統查詢。

是否有任何其他函數來檢查路徑是否有效? 試試這個:

File file = new File("c:\fileName"); 
if (!file.isDirectory()) 
    file = file.getParentFile(); 
if (file.exists()){ 
    ... 
} 
相關問題