陳鍾誠的程式作品集 -- 執行命令列程式 (Runtime)

程式作品

C 語言

Java

C#

JavaScript

常用函數

文字處理

遊戲程式

衛星定位

系統程式

資料結構

網路程式

自然語言

人工智慧

機率統計

資訊安全

等待完成

訊息

相關網站

參考文獻

最新修改

簡體版

English

範例:命令列指令呼叫

import java.util.*;
import java.io.*;
 
public class TestExec
{
    public static void main(String args[])
    {
        try
        {            
            Runtime rt = Runtime.getRuntime();
//            Process proc = rt.exec("javac");
//            Process proc = rt.exec("javac");
            Process proc = rt.exec("start http://www.google.com/");
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            System.out.println("<ERROR>");
            while ( (line = br.readLine()) != null)
                System.out.println(line);
            System.out.println("</ERROR>");
            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

範例:命令列指令呼叫 : 將輸出轉到檔案

import java.util.*;
import java.io.*;
 
public class Runtime1 {
    public static void main(String args[]) {
        exec("start http://www.google.com.tw/");
    }
 
    public static boolean exec(String command) { try {            
        String osName = System.getProperty("os.name" );
        String[] cmd = { "cmd.exe", "/C", command } ;
        if (osName.equals( "Windows 95" ))
            cmd[0] = "command.exe";            
        Runtime rt = Runtime.getRuntime();
        System.out.println("Execute " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
        Process proc = rt.exec(cmd);
        // any error message?
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");                        
        // any output?
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");                
        // kick them off
        errorGobbler.start();
        outputGobbler.start();
        // any error???
        int exitVal = proc.waitFor();
        System.out.println("ExitValue: " + exitVal);        
        return true;
    } catch (Throwable t) { t.printStackTrace(); return false;} }
}
 
class StreamGobbler extends Thread {
    InputStream is;
    String type;
 
    StreamGobbler(InputStream is, String type) {
        this.is = is;
        this.type = type;
    }
 
    public void run() { try {
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line=null;
        while ( (line = br.readLine()) != null)
            System.out.println(type + ">" + line);    
    } catch (IOException ioe) { ioe.printStackTrace(); }}
}

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License