当Runtime.getRuntime().exec调用Linux批处理文件时找不到其物理目录

5

我有一个Java应用程序,并使用Runtime.getRuntime().exec调用批处理文件。当我使用Runtime.getRuntime().exec调用Linux批处理文件时,批处理文件无法找到自己的目录。我在批处理文件中使用pwd命令,但它返回的是应用程序路径。我需要批处理文件自己的物理路径。我该如何做?


1
你应该使用 $0 而不是 pwd,但这与 Java 没有任何关系。这可能甚至属于 http://superuser.com/ 而不是 stackoverflow。 - Holger
在Linux中,用于批处理的文件通常被称为"脚本"。 - Am_I_Helpful
如果您想更改工作目录,请参阅https://dev59.com/Rmw15IYBdhLWcg3wIYO_ - mwerschy
https://dev59.com/yXVD5IYBdhLWcg3wL4cA - Holger
3个回答

4

您需要使用ProcessBuilder来完成这个任务:

ProcessBuilder builder = new ProcessBuilder( "pathToExecutable");
builder.directory( new File( "..." ).getAbsoluteFile() ); //sets process builder working directory

对于正确的、跨平台的解决方案,点赞(+1)。 - Boris the Spider

0

试试这个。对我来说有效。

        Process p = Runtime.getRuntime().exec("pwd");
        BufferedReader bri = new BufferedReader
                (new InputStreamReader(p.getInputStream()));
        BufferedReader bre = new BufferedReader
                (new InputStreamReader(p.getErrorStream()));
        String line;
        while ((line = bri.readLine()) != null) {
            System.out.println(line);
        }
        bri.close();
        while ((line = bre.readLine()) != null) {
            System.out.println(line);
        }
        bre.close();
        p.waitFor();

0

批处理文件是一种脚本文件,通常使用 Microsoft 的命令提示符 shell('cmd.exe')在 Windows 中运行。它们包含一系列特定于该 shell 的命令,因此无法与 Unix shell(如 Bash)一起使用,除非你特别指定文件扩展名为 '.bat'。

如果你实际上是指 Unix 'shell 脚本',而不是特定于 Microsoft 的 '批处理文件',那么最好使用 ProcessBuilder 类,因为它比 Runtime 的 exec() 方法提供更大的灵活性。

要使用 ProcessBuilder 在其自己的目录中运行脚本,请将构建器的目录设置为指向脚本的相同目录,如下所示:

// Point to wherever your script is stored, for example:
String script    = "/home/andy/bin/myscript.sh";
String directory = new File(script).getParent();

// Point to the shell that will run the script
String shell = "/bin/bash";

// Create a ProcessBuilder object
ProcessBuilder processBuilder = new ProcessBuilder(shell, script);

// Set the script to run in its own directory
processBuilder.directory(new File(directory));

// Run the script
Process process = processBuilder.start();

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