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() 返回字符串

我应该怎么办 ?

感谢您的回复 :)

4

5 回答 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();
于 2013-09-26T11:10:33.710 回答
1

您可能正在使用 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);
于 2010-06-13T14:08:38.883 回答
0

like write code for real path

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

here u can get real path ..........

于 2013-01-04T06:55:38.017 回答
0

只需查看 lol 的内容,当您调用x.getPath(). 我猜这不是绝对路径,并且文件已创建,但不是您期望的位置。

x是一个绝对路径的Java.io.File我们getCanonicalPath()

于 2010-06-13T13:40:34.537 回答
0

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

if (!"/home/pc/example.txt".equals(x.getPath())) throw new RuntimeException();
于 2010-06-13T14:28:06.760 回答