java使用Runtime.getRuntime().exec(command)运行E:\info\test\online_ide\小花\JavaTest文件夹下的do.bat文件的demo
时间: 2023-10-08 22:09:00 浏览: 31
可以使用以下代码运行E:\info\test\online_ide\小花\JavaTest文件夹下的do.bat文件:
```
String command = "cmd /c start E:\\info\\test\\online_ide\\小花\\JavaTest\\do.bat";
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
```
这里使用了cmd命令来执行do.bat文件,并使用start命令来启动一个新窗口运行该命令。同时使用process.waitFor()来等待命令执行完成。
相关问题
java使用Runtime.getRuntime().exec(command)运行dir命令的demo
下面是一个简单的Java代码示例,演示如何使用 `Runtime.getRuntime().exec()` 方法运行 `dir` 命令:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo {
public static void main(String[] args) {
try {
// 创建 Runtime 实例
Runtime runtime = Runtime.getRuntime();
// 执行 dir 命令
Process process = runtime.exec("cmd /c dir");
// 获取命令执行结果
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们首先创建了一个 `Runtime` 实例,然后使用 `runtime.exec()` 方法执行 `cmd /c dir` 命令。`cmd /c` 表示在执行命令之前先执行一次 `cmd.exe`,而 `dir` 命令则是列出当前目录下的文件和文件夹。最后,我们通过 `BufferedReader` 读取命令的执行结果并打印出来。
在JAVA中通过Runtime.getRuntime().exec运行Linux虚拟机中的脚本
可以使用`Runtime.getRuntime().exec`在Java中运行Linux虚拟机中的脚本。下面是一个简单的例子:
```java
try {
// 调用虚拟机中的脚本
Process p = Runtime.getRuntime().exec("/usr/local/bin/myscript.sh");
// 获取脚本的输出结果
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
```
在上面的例子中,`exec`方法接收一个字符串参数,该参数是要在虚拟机中执行的命令或脚本。在这个例子中,我们调用了一个名为`myscript.sh`的脚本。然后我们通过`BufferedReader`从脚本的输出中读取每一行,并将其打印到控制台上。
需要注意的是,`exec`方法执行命令或脚本时会阻塞当前线程,直到命令或脚本执行完毕。如果需要在后台执行命令或脚本,可以使用`ProcessBuilder`类。