總網頁瀏覽量

2016年4月19日 星期二

[Java] 開起外部檔案 之一

想要執行一個 class 檔, 來執行另一個 class 檔.
所以我就先從 java 執行外部檔案 做為關鍵字往下做.

import java.util.*;
import java.io.*;
 
Opentest001.java [1]
 
import java.util.*;
import java.io.*;

public class Opentest001 {
    public static void main (String args[]) {
        try {          
            Runtime rt = Runtime.getRuntime ();
            System.out.println ("Process Runtime_getRuntime: " + rt);
            Process proc = rt.exec ("javac");
            System.out.println ("Process Process_exec: " + proc);
            int exitVal = proc.exitValue ();
            System.out.println ("Process exitValue: " + exitVal);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}
 
Opentest001.java看到,
藉由 Runtime.getRuntime() 取得目前應用程式運行物件,
並呼叫 Runtime的.exec() 執行() 內的指定命令(command), 
以目前來看, 就是利用cmd執行 javac, 將傳回值放到 Process 的 proc.
 
接下來利用 Process 的 exitValue() 的到程序結束的回傳值.

 
- - - - -
java Opentest001
 
Process Runtime_getRuntime: java.lang.Runtime@15db9742
Process Process_exec: java.lang.ProcessImpl@6d06d69c
java.lang.IllegalThreadStateException: process has not exited
        at java.lang.ProcessImpl.exitValue(ProcessImpl.java:443)
        at Opentest001.main(Opentest001.java:12)
- - - - - 
 
出現了執行錯誤, 看 getRuntime(), 靜態函式來取得 Rumtime 物件, 
利用 exec() 執行外部執行檔 javac, 取得回傳值在輸出到標準輸出.

exec 會創建新的 process 以執行 javac, 但是呼叫 exitValue()後, 
javac 的執行還未結束, JVM 就會丟出例外 IllegalThreadStateException,
 
所以要等 外部執行程序執行完, 就要利用 waitFor(). 

Opentest004.java 
 
import java.util.*;
import java.io.*;

public class Opentest004 {
    public static void main (String args[]) {
        try {           
            Runtime rt = Runtime.getRuntime ();
            System.out.println ("Process Runtime_getRuntime: " + rt);
            Process proc = rt.exec ("javac");
            System.out.println ("Process Process_exec: " + proc);
            int waitVal = proc.waitFor();
            System.out.println ("Process exitValue: " + waitVal);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}

- - - - -
Process Runtime_getRuntime: java.lang.Runtime@15db9742
Process Process_exec: java.lang.ProcessImpl@6d06d69c
Process waitVal: 2
- - - - -

接下來要得到 commmand 執行後的內容

Opentest006.java

import java.util.*;
import java.io.*;

public class Opentest006{
    public static void main(String args[]){
        try{
            Runtime rt = Runtime.getRuntime();
  String s[] = {"javac if_test.java",
                "java if_test",
                "javac"};
            Process proc = rt.exec(s[1]);
            String line = null;
           
            InputStream stderr = proc.getErrorStream ();
            InputStreamReader esr = new InputStreamReader (stderr);
            BufferedReader ebr = new BufferedReader (esr);

            System.out.println ("javac output:");       
            while ( (line = ebr.readLine ()) != null)
                System.out.println(line);           
            System.out.println ("javac end");
           
            InputStream stdout = proc.getInputStream ();
            InputStreamReader osr = new InputStreamReader (stdout);
            BufferedReader obr = new BufferedReader (osr);
           
            System.out.println ("<output>");
            while ( (line = obr.readLine ()) != null)
                System.out.println(line);
            System.out.println ("</output>");

            int exitVal = proc.waitFor ();
            System.out.println ("Process exitValue: " + exitVal);   
           
        }catch(Exception e){
           
        }
    }
}
 
if_test.java 
 
public class if_test{
    public static void main(String args[]){
        boolean i = true;
       
        if(i ){
            System.out.println(" Hello World!");
        }else{
            int y = 5;
        }
    }
}
 
我將要執行的 Command 先存放到 Sting s[]中,
當我在執行 s[0], s[1]時會發現程式執行會利用 getInputStromg() 將內容顯示至標準輸出, 而在 s[2] 時卻以 getErrorStream() 印出, 兩者分別將串流儲存在 stderr 和 stdout 裡面, 所以現在就會要求這些串流盡快輸出
 
 
Runtime[4]
每個 Java 應用程式都擁有單一個實做類別這個類別給予應用程式一個執行環境. 可以利用getRuntime method 獲得執行實的資訊. 這個應用程式不能創建初一個屬於自己的類別class.

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method. An application cannot create its own instance of this class 
 
在 Oracle 文件中聲明:

Class Process
- java.lang.object
 - java.lang.Runtime
 
public class Runtime extends Object
 
僅列出幾個會用的, 其他官網看.
 

 
static RuntimegetRuntime()
Returns the runtime object associated with the current Java application.
回傳目前執行中的 java 應用程是之物件.
Process exec(String command)
Executes the specified string command in a separate process.
Process exec(String[] cmdarray)
Executes the specified command and arguments in a separate process.
Process exec(String[] cmdarray, String[] envp)
Executes the specified command and arguments in a separate process with the specified environment.
Process exec(String[] cmdarray, String[] envp, File dir)
Executes the specified command and arguments in a separate process with the specified environment and working directory.
Process exec(String command, String[] envp)
Executes the specified string command in a separate process with the specified environment.
Process exec(String command, String[] envp, File dir)
Executes the specified string command in a separate process with the specified environment and working directory.
 
 
 
 
Process[2][3]
  
Process 是 java.lang.Process 底下的類別, 提供從程序的輸入, 執行到輸出到行程, 等待
執行完成, 檢查程序進行的狀態, 刪除程序的進行方法.
 
在 Oracle 文件中聲明:

Class Process
- java.lang.object
 - java.lang.Process


public abstract class Process extends Object
 
 
 
Method Summary
 

Modifier and Type Method and Description
abstract void destroy()
Kills the subprocess.
刪除子程序
abstract int exitValue()
Returns the exit value for the subprocess.
返回子程序
abstract InputStream getErrorStream()
Returns the input stream connected to the error output of the subprocess.
得到錯誤訊息
abstract InputStream getInputStream()
Returns the input stream connected to the normal output of the subprocess.
進行輸出
abstract OutputStream getOutputStream()
Returns the output stream connected to the normal input of the subprocess.
進行輸入
abstract int waitFor()
Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.
在當機前進行等待, 若有必要由該Process對象的進程已經終止.
 
 
 
 
[1] http://yindingtsai.blogspot.tw/2010/01/runtimeexec.html
[2] https://docs.oracle.com/javase/7/docs/api/java
  /lang/Process.html#getErrorStream%28%29
[3] http://tw.gitbook.net/java/lang/java_lang_runtime.html
[4] https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html













沒有留言:

張貼留言