简体   繁体   English

如何在 java 中执行“cd”命令,然后执行 linux 命令

[英]How to execute 'cd' command and then a linux command in java

I have directory /tmp then I need to execute cd and go to that folder.我有目录 /tmp 然后我需要执行 cd 和 go 到该文件夹。 Then I need to execute./executeScript然后我需要执行./executeScript

Preparation准备

To start solving the problem, I created a directory /home/vulpini99/tmp .为了解决这个问题,我创建了一个目录/home/vulpini99/tmp In this directory, I created the bash-script test.sh , which will open firefox for us:在这个目录中,我创建了 bash-script test.sh ,它将为我们打开 firefox:

firefox

Then I created a java-file named LinuxCommand.java in the directory /home/vulpini99 .然后我在目录/home/vulpini99中创建了一个名为LinuxCommand.java的 java 文件。

Main part主要部分

cd is just an internal shell command and not an executable program, so I suggest to just use the full path of the bash-script. cd只是一个内部 shell 命令而不是可执行程序,所以我建议只使用 bash-script 的完整路径。 So the command we want to execute is所以我们要执行的命令是

bash /home/vulpini99/tmp/test.sh . bash /home/vulpini99/tmp/test.sh

In Java, you can use Runtime for this purpose:在 Java 中,您可以为此目的使用Runtime

import java.io.IOException;

public class LinuxCommand {

    public static void main(String[] args) {
        Runtime run = Runtime.getRuntime();
        try {
            run.exec("bash /home/vulpini99/tmp/test.sh");
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM