java - Java中Process类的用途是什么?

标签 java runtime.exec

Runtime objRuntime = Runtime.getRuntime();
String strBackupString = "mysqldump -u " + userName + " -p" + password + " " + dbName;
Process objProcess = objRuntime.exec(strBackupString);

这用于数据库的备份。但到底发生了什么?任何人都可以让我解释一下,RuntimeProcess 类的目的是什么?

这个类是用来表现我们在命令提示符下输入命令的吗?那么如果我想打开记事本,我应该传递什么给 objRuntime.exec() 呢?我们一调用 exec 方法,命令就执行了吗?如果是,那么 Process 在这里起什么作用?实在是看不懂这两个类。请让我明白。提前致谢:)

最佳答案

如有疑问,请始终查阅 API:

java.lang.Process

The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.

Runtime.exec(String command)

Executes the specified system command in a separate process.

是的,Runtime.exec 可以执行您通常在系统命令提示符下键入的命令。这几乎不是独立于平台的解决方案,但有时需要它。返回的 Process 对象让您可以控制它、终止它,重要的是,有时还可以重定向它的标准输入/输出/错误流。

相关问题

API 链接


notepad.exe 例子

如前所述,这是依赖于平台的,但这段代码适用于我的 Windows 机器;它启动 notepad.exe,并尝试从当前工作目录打开 test.txt。然后程序等待进程终止,并打印它的exit code。 .

public class ExecExample {
    public static void main(String[] args) throws Exception {
        Process p = Runtime.getRuntime().exec("notepad.exe test.txt");      
        System.out.println("Waiting for notepad to exit...");
        System.out.println("Exited with code " + p.waitFor());
    }
}

关于java - Java中Process类的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2798425/

相关文章:

java - 如何区分两个 JodaTime LocalTime 时间戳?

java - 如何在java运行时exec方法中给出长路径?

java - Dubbo服务启动错误:Error creating bean with name 'userServiceImpl' nested exception is org. I0Itec.zkclient.exception.ZkTimeoutException

java - 我正在尝试使用 Mockito 2 模拟最终的 java 类,类被模拟,但我仍然收到未完成的 stub 异常

java - 如何在Java类中执行cmd命令?

java - Runtime.getRuntime().exec - 执行 osql 查询

java - 将字符串作为输入传递到 Java Runtime.exec()

java.io.IOException : The pipe is being closed is thrown on Windows but works fine on Linux 异常

java - 如何使用 svnClientAdapter java API getLogMessages(java.io.File path, SVNRevision revisionStart, SVNRevision revisionEnd)

java - 修改/替换拦截器内的 ClientHttpResponse 主体(ClientHttpRequestInterceptor)