Runtime objRuntime = Runtime.getRuntime();
String strBackupString = "mysqldump -u " + userName + " -p" + password + " " + dbName;
Process objProcess = objRuntime.exec(strBackupString);
这用于数据库的备份。但到底发生了什么?任何人都可以让我解释一下,Runtime
和 Process
类的目的是什么?
这个类是用来表现我们在命令提示符下输入命令的吗?那么如果我想打开记事本,我应该传递什么给 objRuntime.exec()
呢?我们一调用 exec 方法,命令就执行了吗?如果是,那么 Process
在这里起什么作用?实在是看不懂这两个类。请让我明白。提前致谢:)
最佳答案
如有疑问,请始终查阅 API:
The
ProcessBuilder.start()
andRuntime.exec
methods create a native process and return an instance of a subclass ofProcess
that can be used to control the process and obtain information about it. The classProcess
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.Executes the specified system command in a separate process.
是的,Runtime.exec
可以执行您通常在系统命令提示符下键入的命令。这几乎不是独立于平台的解决方案,但有时需要它。返回的 Process
对象让您可以控制它、终止它,重要的是,有时还可以重定向它的标准输入/输出/错误流。
相关问题
- Is java Runtime.exec platform independent?
- How to create a process in Java
- Get output from a process
- Runtime.getRuntime().exec()
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/