5

我不能使用 Process("dir/e.exe") 因为 e 需要在它自己的目录上执行,否则它不能访问它的资源。但是每当我尝试更改工作目录时都会收到异常:

Process("e.exe", new File(dir)) 
Process("e.exe", new File("\"+ dir))
Process("e.exe", new File(new File(dir).getCanonicalPath()))  

Caused by: java.io.IOException: Cannot run program "e.exe" (in directory ".
\dir"): CreateProcess error=2, The system cannot find the file specified

这些不起作用,它们给了我完全相同的错误。有什么选择吗?

编辑:这是我的目录的外观:

MyFolder:
|-app.jar
|-folderWithExe
  \-e.exe
4

3 回答 3

3

好的,这就是我所拥有的(脏代码,仅用于演示目的)

首先,我的目录结构(subdir是一个子目录):

cdshines@v3700:~/test|⇒  ls -R
.:
log  pb.scala  subdir

./subdir:
ls

然后我的代码:

import java.lang.ProcessBuilder
import java.io.File

val pb = new ProcessBuilder("ls", "../")
pb.directory(new File("subdir"))
pb.redirectOutput(ProcessBuilder.Redirect.to(new File("log")))
val p = pb.start
p.waitFor
println(p.exitValue)

让我们来看看:

cdshines@v3700:~/test|⇒  scala pb.scala
0
cdshines@v3700:~/test|⇒  cat log
log
pb.scala
subdir

这是您对这段代码的期望吗?在我看来很好。

一般来说:

1)使用创建 ProcessBuldernew ProcessBuilder("application", "arg0", "arg1")

2)设置其目录"pb.directory(new File("path/to/dir"))"

Process3) 使用orProcessBuilder方法获取输出或退出代码等。

使用 Scala,您可以使用Source它来加快编写速度(甚至更脏,但足以玩转):

scala.io.Source.fromInputStream(
  new ProcessBuilder("ls", "../")
  .directory(new File("subdir"))
  .start
  .getInputStream).getLines.mkString("\n")
于 2013-09-09T21:14:48.253 回答
2

Try "./e.exe" or put "." on the path.

(Edited for clarity.)

Postmortem: the question is, what could you do to solve this quickly without SO? You really want a message that says: "Couldn't find the program to run after trying these locations..." Or even, perhaps under something like -Dprocess.debug, "There is a file named foo in the current directory but I can't run it because..."

For the record:

import sys.process._
import java.io.File

//System setSecurityManager new SecurityManager
Console println Process("./tester", new File("subdir")).lines.toList

Showing that path matters:

apm@mara:~/tmp/cdtest$ echo $PATH
/home/apm/go1.1/go/bin:/home/apm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
apm@mara:~/tmp/cdtest$ vi runit.scala
apm@mara:~/tmp/cdtest$ scalam runit.scala
java.io.IOException: Cannot run program "tester" (in directory "subdir"): error=2, No such file or directory
apm@mara:~/tmp/cdtest$ grep tester runit.scala 
Console println Process("tester", new File("subdir")).lines.toList
apm@mara:~/tmp/cdtest$ PATH=$PATH:.
apm@mara:~/tmp/cdtest$ scalam runit.scala
List(file1, file2, tester)
于 2013-09-09T20:03:36.550 回答
0

此代码应该可以解决您的问题

    ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c", "cd \"D:\\folder\\With\\Exe\" && e.exe");
    Process p = builder.start();
    p.waitFor();
于 2014-11-30T13:17:43.160 回答