Java Process getErrorStream() 方法



描述

Java Process getErrorStream() 方法获取子进程的错误流。该流获取从由该 Process 对象表示的进程的错误输出流中管道传输的数据。

声明

以下是 java.lang.Process.getErrorStream() 方法的声明

public abstract InputStream getErrorStream()

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

参数

返回值

此方法返回连接到子进程错误流的输入流。

异常

检查记事本进程错误流示例

以下示例显示了 Process getErrorStream() 方法的使用。我们为记事本可执行文件创建了一个 Process 对象。然后使用 getErrorStream() 方法检索记事本进程的错误流。使用错误流的 available() 方法,我们读取可用的错误。然后使用 Thread.sleep() 方法,程序暂停 10 秒,最后使用 destroy() 方法终止进程。

package com.tutorialspoint; import java.io.InputStream; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process..."); String[] cmds = {"notepad.exe"}; Process p = Runtime.getRuntime().exec(cmds); // get the error stream of the process and print it InputStream error = p.getErrorStream(); for (int i = 0; i < error.available(); i++) { System.out.println("" + error.read()); } // wait for 10 seconds and then destroy the process Thread.sleep(10000); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } } }

输出

让我们编译并运行以上程序,这将产生以下结果:

Creating Process...

检查计算器进程错误流示例

以下示例显示了 Process getErrorStream() 方法的使用。我们为计算器可执行文件创建了一个 Process 对象。然后使用 getErrorStream() 方法检索计算器进程的错误流。使用错误流的 available() 方法,我们读取可用的错误。然后使用 Thread.sleep() 方法,程序暂停 10 秒,最后使用 destroy() 方法终止进程。

package com.tutorialspoint; import java.io.InputStream; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process..."); String[] cmds = {"calc.exe"}; Process p = Runtime.getRuntime().exec(cmds); // get the error stream of the process and print it InputStream error = p.getErrorStream(); for (int i = 0; i < error.available(); i++) { System.out.println("" + error.read()); } // wait for 10 seconds and then destroy the process Thread.sleep(10000); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } } }

输出

让我们编译并运行以上程序,这将产生以下结果:

Creating Process...

检查 Windows 资源管理器进程错误流示例

以下示例显示了 Process getErrorStream() 方法的使用。我们为 Windows 资源管理器可执行文件创建了一个 Process 对象。然后使用 getErrorStream() 方法检索 Windows 资源管理器进程的错误流。使用错误流的 available() 方法,我们读取可用的错误。然后使用 Thread.sleep() 方法,程序暂停 10 秒,最后使用 destroy() 方法终止进程。

package com.tutorialspoint; import java.io.InputStream; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process..."); String[] cmds = {"explorer.exe"}; Process p = Runtime.getRuntime().exec(cmds); // get the error stream of the process and print it InputStream error = p.getErrorStream(); for (int i = 0; i < error.available(); i++) { System.out.println("" + error.read()); } // wait for 10 seconds and then destroy the process Thread.sleep(10000); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } } }

输出

让我们编译并运行以上程序,这将产生以下结果:

Creating Process...
java_lang_process.htm
广告