我在Java中遇到Runtime.exec()问题 我的代码:
String lol = "/home/pc/example.txt";
String[] b = {"touch", lol};
try {
Runtime.getRuntime().exec(b);
} catch(Exception ex) {
doSomething(ex);
}
它运行良好,但当我尝试变换变量“lol”文件时不会在硬盘中创建
例如:
String lol = x.getPath();
其中getPath()返回String
我该怎么办?
感谢您的回复:)
答案 0 :(得分:5)
以下是您的问题的解决方案。我遇到了类似的问题,通过对输出目录进行拼写,这对我有用,它应该在该工作目录中执行文件的输出。
ProcessBuilder proc = new ProcessBuilder("<YOUR_DIRECTORY_PATH>" + "abc.exe"); // <your executable path>
proc.redirectOutput(ProcessBuilder.Redirect.INHERIT); //
proc.directory(fi); // fi = your output directory
proc.start();
答案 1 :(得分:1)
您可能正在使用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);
这不起作用,因为os会搜索名为“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);
答案 2 :(得分:0)
当你打电话给x.getPath()
时,只需看一下lol的内容。我猜它不是一个绝对的路径,文件被创建,但不是你期望的那样。
对于绝对路径,x
是Java.io.File
我getCanonicalPath()
。
答案 3 :(得分:0)
如果在将字符串设置为文字“/home/pc/example.txt”时代码有效,并且x.getPath也返回相同的值,那么它必须工作 - 就这么简单。这意味着x.getPath()实际上返回了其他内容。也许字符串中有空格?尝试直接比较字符串:
if (!"/home/pc/example.txt".equals(x.getPath())) throw new RuntimeException();
答案 4 :(得分:0)
喜欢为真实路径编写代码
String path = request.getSession().getServletContext().getRealPath("/");
这里你可以得到真正的路径..........