Java - Runtime.getRuntime().exec() 是什么意思?

3
我在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()返回字符串。

我该怎么办?

谢谢您的回复 :)


我在Linux上没有做过太多的Java,但可能是权限问题——也许沙盒不允许您在家目录之外创建文件?这只是一个猜测,也许值得探究一下。 - Kaleb Brasee
谢谢回复,但我已经设置了chmod 777,当我不使用getPath()时,文件会出现。 - kunkanwan
注意:如果命令执行失败,Runtime#exec()不会抛出任何异常。您需要读取其输出或错误流。还请参阅此链接(所有4页)http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html - BalusC
5个回答

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

你可能正在使用 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" 的应用程序。
现在,你可能会想:"什么鬼?为什么?"
因为方法 Runtime.getRuntime().exec(String cmd); 会将你的字符串按空格分割。 而 Runtime.getRuntime().exec(String[] cmdarray); 则不会分割。所以,你必须自己来处理:

String[] cmd = {"touch", "/home/pc/example.txt"};
Runtime.getRuntime().exec(cmd);

0

比如编写真实路径的代码

String path = request.getSession().getServletContext().getRealPath("/");

在这里,你可以获取真实路径..........


0

简单地查看lol的内容,当你调用x.getPath()时。我猜它不是绝对路径,文件得到创建了,但不在你期望的位置。

如果xJava.io.File,请使用getCanonicalPath()获取绝对路径。


好的观点,但是如果我打印x.getPath()得到的结果等于"/home/pc/example.txt",那应该是没问题的。当我使用Runtime.getRuntime().exec("touch /home/pc/example.txt")时,它能正常工作,但是当我尝试使用函数时,它就不起作用了。 - kunkanwan

0

如果当您将字符串设置为文字"/home/pc/example.txt"时,代码能够正常工作且x.getPath也返回相同的值,则它必须工作-就是这么简单。这意味着x.getPath()实际上返回了其他内容。也许字符串中有空格?尝试直接比较字符串:

if (!"/home/pc/example.txt".equals(x.getPath())) throw new RuntimeException();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接