您可能正在使用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