Java ProcessBuilder redirectErrorStream() 方法



描述

Java ProcessBuilder redirectErrorStream(boolean redirectErrorStream) 方法設定此程序構建器的 redirectErrorStream 屬性。如果此屬性為 true,則此物件 start() 方法隨後啟動的子程序生成的任何錯誤輸出將與標準輸出合併,以便可以使用 Process.getInputStream() 方法讀取兩者。這使得將錯誤訊息與其對應的輸出關聯起來更容易。初始值為 false。

宣告

以下是 java.lang.ProcessBuilder.redirectErrorStream() 方法的宣告

public ProcessBuilder redirectErrorStream(boolean redirectErrorStream)

引數

redirectErrorStream − 新的屬性值

返回值

此方法返回此程序構建器

異常

使用 Process Builder 示例設定記事本的重定向錯誤流

以下示例演示了 ProcessBuilder redirectErrorStream() 方法的用法。在這個程式中,我們建立了一個字串陣列,並向其中添加了 notepad.exe 和 test.txt。使用該列表,我們初始化了一個 ProcessBuilder 例項。現在使用 redirectErrorStream() 方法,我們設定了重定向錯誤流標誌,然後檢索重定向錯誤流並列印相應的對映標誌。

package com.tutorialspoint;

public class ProcessBuilderDemo {

   public static void main(String[] args) {

      // create a new list of arguments for our process
      String[] list = {"notepad.exe", "test.txt"};

      // create the process builder
      ProcessBuilder pb = new ProcessBuilder(list);

      // Redirect the errorstream
      pb.redirectErrorStream(true);
      System.out.println(pb.redirectErrorStream());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

true

使用 Process Builder 示例設定計算器的重定向錯誤流

以下示例演示了 ProcessBuilder redirectErrorStream() 方法的用法。在這個程式中,我們建立了一個字串陣列,並向其中添加了 calc.exe。使用該列表,我們初始化了一個 ProcessBuilder 例項。現在使用 redirectErrorStream() 方法,我們設定了重定向錯誤流標誌,然後檢索重定向錯誤流並列印相應的對映標誌。

package com.tutorialspoint;

public class ProcessBuilderDemo {

   public static void main(String[] args) {

      // create a new list of arguments for our process
      String[] list = {"calc.exe"};

      // create the process builder
      ProcessBuilder pb = new ProcessBuilder(list);

      // Redirect the errorstream
      pb.redirectErrorStream(true);
      System.out.println(pb.redirectErrorStream());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

true

使用 Process Builder 示例設定 Windows 資源管理器的重定向錯誤流

以下示例演示了 ProcessBuilder redirectErrorStream() 方法的用法。在這個程式中,我們建立了一個字串陣列,並向其中添加了 explorer.exe。使用該列表,我們初始化了一個 ProcessBuilder 例項。現在使用 redirectErrorStream() 方法,我們設定了重定向錯誤流標誌,然後檢索重定向錯誤流並列印相應的對映標誌。

package com.tutorialspoint;

public class ProcessBuilderDemo {

   public static void main(String[] args) {

      // create a new list of arguments for our process
      String[] list = {"explorer.exe"};

      // create the process builder
      ProcessBuilder pb = new ProcessBuilder(list);

      // Redirect the errorstream
      pb.redirectErrorStream(true);
      System.out.println(pb.redirectErrorStream());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

true
java_lang_processbuilder.htm
廣告