在不同的目录中使用 Java 的 exec 运行 .sh 文件? [英] Running .sh files with Java's exec in a different directory?

查看:37
本文介绍了在不同的目录中使用 Java 的 exec 运行 .sh 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Java 程序 MyAwesomeProgram,它使用 Process 的 exec 函数在本地运行 bash 命令.我的代码位于/home/a/b/c 中,我需要运行的 .sh 文件位于/home/a/b/d 中.但是,当我运行我的代码时:

I'm writing a Java program MyAwesomeProgram that uses Process' exec function to run bash commands locally. My code is located in /home/a/b/c, and there are .sh files located in /home/a/b/d that I need to run. However, when I run my code:

Process p;
Runtime rt = new Runtime.getRuntime();
p = rt.exec("./home/a/b/d/shell.sh");
p.waitFor();

我收到一个错误:

Exception in thread "main" java.io.IOException: Cannot run program "./home/a/b/d/shell.sh": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
at java.lang.Runtime.exec(Runtime.java:593)
at java.lang.Runtime.exec(Runtime.java:431)
at java.lang.Runtime.exec(Runtime.java:328)
at MyAwesomeProgram.main(MyAwesomeProgram.java:186)
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
at java.lang.ProcessImpl.start(ProcessImpl.java:65)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)

我相信这只是格式化 exec 命令字符串的错误,但是到目前为止我还没有找到解决方案.我哪里搞砸了?任何其他有效使用 exec 的提示/技巧将不胜感激,但完全可选.谢谢!

I believe this is just a mistake in formatting the exec command String, however I haven't been able to find a solution thus far. Where have I messed up? Any other tips/tricks for using exec effectively would be appreciated, but completely optional. Thanks!

我让代码正常工作,这是我得到的几个目录引用以及Woot4Moo所说的问题.

I got the code working, it was an issue with a couple directory references I got backwards as well as what Woot4Moo said.

推荐答案

如果你的程序存在于:

/home/a/b/c

并且您的脚本位于:

/home/a/b/d

并且您使用了 . 您不在正确的目录中.您想使用以下路径执行它:

and you use the . you are not in the right directory. You want to exec it with the following path:

../d/script.sh

. 表示使用当前目录 + 您的字符串.所以本质上你的输入如下:

The . says use the current directory + your string. So in essence your input is the following:

/home/a/b/c/home/a/b/d

.. 允许你上一个目录,如果你在:

The .. allows you to go up one directory which if you are at :

/home/a/b/c

你想要到达:

/home/a/b

这篇关于在不同的目录中使用 Java 的 exec 运行 .sh 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆