您可能正在使用 ajava.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);