📜  Java Java类

📅  最后修改于: 2022-05-13 01:54:25.186000             🧑  作者: Mango

Java Java类

抽象Process类是一个进程,即一个正在执行的程序。 Process提供的方法用于执行输入、输出、等待进程完成、检查进程的退出状态和销毁进程。

  • 它扩展类Object
  • 它主要用作运行时类中 exec() 创建的对象类型的超类。
  • ProcessBuilder.start()Runtime.getRuntime.exec()方法创建一个本地进程并返回一个Process子类的实例,该实例可用于控制进程并获取有关它的信息。
  • ProcessBuilder.start() 是创建流程的首选方式。

ProcessBuilder.start() vs Runtime.getRuntime.exec(): ProcessBuilder 允许我们将子进程的标准错误重定向到它的标准输出中。现在我们不需要两个单独的线程,一个从stdout读取,一个从stderr读取。

构造函数

  • Process():这是唯一的构造函数。

    方法:

    1. void destroy():杀死子进程。
      Syntax: public abstract void destroy().
      Returns: NA.
      Exception: NA.
      
      // Java code illustrating destroy() 
      // method for windows operating system
      public class ProcessDemo 
          public static void main(String[] args) 
          {
              try 
              {
                    
                  // create a new process
                  System.out.println("Creating Process");
                    
                  ProcessBuilder builder = new ProcessBuilder("notepad.exe");
                  Process pro = builder.start();
            
                  // wait 10 seconds
                  System.out.println("Waiting");
                  Thread.sleep(10000);
            
                  // kill the process
                  pro.destroy();
                  System.out.println("Process destroyed");
            
              } 
                  catch (Exception ex) 
              {
                  ex.printStackTrace();
              }
          }
      }
      

      输出:

      Creating Process
      Waiting
      Process destroyed
      
      // Java code illustrating destroy()
      // method for Mac Operating System
      import java.lang.*;
      import java.io.*;
      class ProcessDemo
      {
          public static void main(String arg[]) throws IOException, Exception
          {
              System.out.println("Creating process");
                    
              //creating process
              ProcessBuilder p = new ProcessBuilder(new String[] 
                              {"open", "/Applications/Facetime.app"});
              Process pro = p.start();
                    
              //waiting for 10 second
              Thread.sleep(10000);
                    
              System.out.println("destroying process");
                    
              //destroying process
              pro.destroy();
          }
      }
      

      输出:

      Creating process
      destroying process
      
    2. int exitValue():此方法返回子进程的退出值。
      Syntax: public abstract int exitValue().
      Returns: This method returns the exit value of 
      the subprocess represented by this Process object. 
      By convention, the value 0 indicates normal termination.
      Exception: IllegalThreadStateException ,
      if the subprocess represented by this Process object has not yet terminated.
      
      // Java code illustrating exitValue() method
      public class ProcessDemo 
      {
          public static void main(String[] args)
          {
              try 
              {
                  // create a new process
                  System.out.println("Creating Process");
                    
                  ProcessBuilder builder = new ProcessBuilder("notepad.exe");
                  Process pro = builder.start();
            
                  // kill the process
                  pro.destroy();
                    
                  // checking the exit value of subprocess
                  System.out.println("exit value: " + pro.exitValue());
            
              } 
                  catch (Exception ex) 
              {
                  ex.printStackTrace();
              }
          }
      }
      

      输出:

      Creating Process
      1
      
    3. abstract InputStream getErrorStream():该方法获取子进程的输入流。
      Syntax: public abstract InputStream getInputStream().
      Returns: input stream that reads input from the process out output stream.
      Exception: NA.
      
      // Java code illustrating
      // getInputStream() method
      import java.lang.*;
      import java.io.*;
      class ProcessDemo
      {
          public static void main(String arg[]) throws IOException, Exception
          {
              // creating the process
              Runtime r = Runtime.getRuntime();
                
              // shell script for loop from 1 to 3
              String[] nargs = {"sh", "-c", "for i in 
                      1 2 3; do echo $i; done"};               
              Process p = r.exec(nargs);
            
              BufferedReader is = 
                  new BufferedReader(new InputStreamReader(p.getInputStream()));
              String line;
                
              // reading the output
              while ((line = is.readLine()) != null)
                
              System.out.println(line);
          }
      }
      

      输出:

      1
      2
      3
      
    4. abstract OutputStream getOutputStream():该方法获取子进程的输出流。流的输出通过管道传输到此 Process 对象表示的进程的标准输入流中。
      Syntax: public abstract OutputStream getOutputStream()
      Returns: the output stream connected to the normal input of the subprocess.
      Exception: NA.
      
      // Java code illustrating 
      // getOutputStream() method
      import java.io.BufferedOutputStream;
      import java.io.OutputStream;
        
      public class ProcessDemo 
      {
          public static void main(String[] args)
          {
              try 
              {
                  // create a new process
                  System.out.println("Creating Process");
                  Process p = Runtime.getRuntime().exec("notepad.exe");
            
                  // get the output stream
                  OutputStream out = p.getOutputStream();
            
                  // close the output stream
                  System.out.println("Closing the output stream");
                  out.close();
              } 
                  catch (Exception ex) 
              {
                  ex.printStackTrace();
              }
          }
      }
      

      输出:

      Creating Process...
      Closing the output stream...
      
    5. abstract InputStream getErrorStream():它返回一个输入流,从进程错误输出流中读取输入。
      Syntax: public abstract InputStream getErrorStream().
      Returns: the input stream connected to the error stream of the subprocess.
      Exception: NA.
      
      // Java code illustrating 
      // getErrorStream() method
      import java.io.InputStream;
        
      public class ProcessDemo
      {
          public static void main(String[] args) 
          {
              try 
              {
                  // create a new process
                  System.out.println("Creating Process");
                    
                  Process p = Runtime.getRuntime().exec("notepad.exe");
            
                  // 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
      
    6. int waitFor():返回进程返回的退出码。在调用它的进程终止之前,此方法不会返回。
      Syntax: public int waitFor().
      Returns: the exit value of the process. By convention, 0 indicates normal termination.
      Exception: throws InterruptedException.
      
      // Java code illustrating 
      // waitFor() method
        
      public class ProcessDemo 
      {
          public static void main(String[] args) 
          {
              try 
              {
                  // create a new process
                  System.out.println("Creating Process");
                  Process p = Runtime.getRuntime().exec("notepad.exe");
            
                  // cause this process to stop
                      // until process p is terminated
                  p.waitFor();
            
                  // when you manually close notepad.exe
                      // program will continue here
                  System.out.println("Waiting over");
              } 
              catch (Exception ex) 
              {
                  ex.printStackTrace();
              }
          }
      }
      

      输出:

      Creating Process...
      Waiting over.