您可能正在使用java.io.File
在這種情況下,getPath()
不會返回絕對路徑。 例如:
System.out.println(System.getProperty("user.dir")); // Prints "/home/pc/"
// This means that all files with an relative path will be located in "/home/pc/"
File file = new File("example.txt");
// Now the file, we are pointing to is: "/home/pc/example.txt"
System.out.println(file.getPath()); // Prints "example.txt"
System.out.println(file.getAbsolutePath()); // Prints "/home/pc/example.txt"
所以,結論是:使用java.io.File.getAbsolutePath()
。
提示:還存在java.io.File.getAbsoluteFile()
方法。調用getPath()
時,這將返回絕對路徑。
我剛纔讀給對方的回答您的評論:
我認爲你做:
String[] cmd = {"touch /home/pc/example.txt"};
Runtime.getRuntime().exec(cmd);
這將無法正常工作,因爲調用的應用程序的操作系統的搜索「touch /home/pc/example.txt
」 。
現在,你在想「WTF?爲什麼?」
因爲方法Runtime.getRuntime().exec(String cmd);
將字符串分割到空格上。 而Runtime.getRuntime().exec(String[] cmdarray);
不分割它。所以,你必須自己做:
String[] cmd = {"touch", "/home/pc/example.txt"};
Runtime.getRuntime().exec(cmd);
在Linux上沒有做過很多的Java,但可能是一個權限問題 - 也許沙箱不允許您在主目錄之外創建文件?只是一個猜測,也許是要看的東西。 – 2010-06-13 13:41:37
Thx for reply,但我設置了chmod 777,當我不使用getPath()文件時出現。 – kunkanwan 2010-06-13 13:53:52
注意:如果命令失敗,'Runtime#exec()'不會引發任何異常。你想閱讀它的輸出或錯誤流。也看到這個鏈接(所有4頁)http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html – BalusC 2010-06-13 14:18:33