Java-Runtime.getRuntime().exec()什么';发生什么事了?
我对Java中的Runtime.exec()有问题 我的代码:Java-Runtime.getRuntime().exec()什么';发生什么事了?,java,runtime,exec,runtime.exec,Java,Runtime,Exec,Runtime.exec,我对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.getP
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()返回字符串
我该怎么办
感谢您的回复:)当您调用x.getPath()
时,只需查看lol的内容即可。我猜这不是一个绝对路径,文件是被创建的,但不是您期望的位置
它x
是一个Java.io.File
usgetCanonicalPath()
的绝对路径。您可能正在使用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(字符串cmd)代码>在空格上拆分字符串。
和Runtime.getRuntime().exec(字符串[]cmdarray)代码>不会将其拆分。所以,你必须自己做:
String[] cmd = {"touch", "/home/pc/example.txt"};
Runtime.getRuntime().exec(cmd);
如果将字符串设置为文本“/home/pc/example.txt”,并且x.getPath也返回相同的值,那么代码就可以工作了——就这么简单。这意味着x.getPath()实际上返回了其他内容。也许字符串中有空格?尝试直接比较字符串:
if (!"/home/pc/example.txt".equals(x.getPath())) throw new RuntimeException();
比如为实路径编写代码
String path = request.getSession().getServletContext().getRealPath("/");
在这里你可以得到真实的路径………这是你问题的解决方案。我遇到了一个类似的问题,通过指定输出目录,它可以在该工作目录中执行文件的输出
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();
ProcessBuilder proc=newprocessbuilder(“+”abc.exe”);//
进程重定向输出(ProcessBuilder.Redirect.INHERIT);//
进程目录(fi);//fi=您的输出目录
proc.start();
在Linux上没有使用过很多Java,但可能是权限问题——也许沙盒不允许您在主目录之外创建文件?只是一个猜测,可能需要查看.Thx以获得回复,但我设置了chmod 777,当我不使用getPath()文件时,会出现该文件。注意:Runtime#exec()
如果命令失败,不会引发任何异常。您希望读取其输出或错误流。也可以看到这个链接(全部4页)很好,但是如果我打印x.getPath()得到的结果等于“/home/pc/example.txt”。应该没问题。当我使用Runtime.getRuntime().exec(“touch/home/pc/example.txt”)时,它工作正常,但当我尝试使用函数时,它不工作。