使用Runtime.getRuntime().exec()方法的几个陷阱 (转)

Process 子类的一个实例,该实例可用来控制进程并获得相关信息。Process 类提供了执行从进程输入、执行输出到进程、等待进程完成、检查进程的退出状态以及销毁(杀掉)进程的方法。 创建进程的方法可能无法针对某些本机平台上的特定进程很好地工作,比如,本机窗口进程,守护进程,Microsoft Windows 上的 Win16/DOS 进程,或者 shell 脚本。
创建的子进程没有自己的终端或控制台

它的所有标准 io(即 stdin、stdout 和 stderr)操作都将通过三个流 (getOutputStream()、getInputStream() 和 getErrorStream()) 重定向到父进程。

子线程的输入是主线程提供的,这个数据对主线程来说就是输出,即jvm线程的OutputStream数据是子线程的stdin;主线程的InputStream是子线程的stdout

 

父进程使用这些流来提供到子进程的输入和获得从子进程的输出。因为有些本机平台仅针对标准输入和输出流提供有限的缓冲区大小,如果读写子进程的输出流或输入流迅速出现失败,则可能导致子进程阻塞,甚至产生死锁。 当没有 Process 对象的更多引用时,不是删掉子进程,而是继续异步执行子进程。 对于带有 Process 对象的 Java 进程,没有必要异步或并发执行由 Process 对象表示的进程。

The class java.lang.Runtime features a static method called getRuntime(), which retrieves the current Java Runtime Environment.
That is the only way to obtain a reference to the Runtime object. With that reference, you can run external programs by invoking the Runtime class's exec() method. Developers often call this method to launch a browser for displaying a help page in HTML. 
There are four overloaded versions of the exec() command: 
public Process exec(String command); 
public Process exec(String [] cmdArray); 
public Process exec(String command, String [] envp); 
public Process exec(String [] cmdArray, String [] envp); 

一个能用的demo:
原则:就是让标准输出和错误输出都使用专门的线程处理,这样可以避免子线程阻塞而导致的错误。建议使用proc.waitFor()

调用的地方:

    public boolean execCommand(String commnad) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd);
            OutputProcessor error = new OutputProcessor(proc.getErrorStream());
            OutputProcessor input = new OutputProcessor(proc.getInputStream());
            error.start();
            input.start();
            int exitCode = proc.waitFor();
            if (exitCode == 0) {
                return true;
            }
            return false;
        } catch (Exception e) {
            LOGGER.info("{}", e.getMessage(), e);
            return false;
        }
    }

处理标准输出和错误输出的线程,因为就是防止子线程阻塞,没简单的输出没有特殊处理:

class OutputProcessor extends Thread {
    private static final Logger LOGGER = LoggerFactory.getLogger(OutputProcessor.class);
    private InputStream inputStream;

    public OutputProcessor(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public void run() {
        try {
            InputStreamReader isr = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                LOGGER.info("{}", line);
            }
        } catch (Exception e) {
            LOGGER.error("", e.getMessage(), e);
        }
    }
}

 





1.Stumbling into an IllegalThreadStateException 
The first pitfall relating to Runtime.exec() is the IllegalThreadStateException. 

import java.util.*;
import java.io.*;
public class BadExecJavac
{
    public static void main(String args[])
    {
        try
        {            
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("javac");
            int exitVal = proc.exitValue();
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t){t.printStackTrace();}
    }
}

If an external process has not yet completed, the exitValue() method will throw an IllegalThreadStateException; that's why this program failed. While the documentation states this fact, why can't this method wait until it can give a valid answer? 
 
A more thorough look at the methods available in the Process class reveals a waitFor() method that does precisely that. In fact, waitFor() also returns the exit value, which means that you would not use exitValue() and waitFor() in conjunction with each other, but rather would choose one or the other. 
The only possible time you would use exitValue() instead of waitFor() would be 
when you don't want your program to block waiting on an external process that may never complete.

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

public class BadExecJavac2
{
    public static void main(String args[])
    {
        try
        {            
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("javac");
            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t){t.printStackTrace();}
    }
}

Unfortunately, a run of BadExecJavac2 produces no output. The program hangs and never completes. 
Why does the javac process never complete? 
Why Runtime.exec() hangs 
The JDK's Javadoc documentation provides the answer to this question: 
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock
本地平台为标准的输入输出流只能提供有限的buffer,因此就不能够立即写子进程的输入流或者是读取子进程的输出流,这就会导致子进程的阻塞甚至死锁

import java.util.*;
import java.io.*;
public class MediocreExecJavac
{
    public static void main(String args[])
    {
        try
        {            
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("javac");
            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();}
    }
}

So, MediocreExecJavac works and produces an exit value of 2. Normally, an exit value of 0 indicates success; any nonzero value indicates an error. The meaning of these exit values depends on the particular operating system.
Thus, to circumvent the second pitfall 
                                                  -- hanging forever in Runtime.exec() --
 if the program you launch produces output or expects input, ensure that you process the input and output streams. 

3.Assuming a command is an executable program

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

public class BadExecWinDir
{
    public static void main(String args[])
    {
        try
        {            
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("dir");//must run as rt.exec("cmd /C dir");
            InputStream stdin = proc.getInputStream();//输入或输出是以jvm为参照物的,命令执行结果会输出到Jvm,对jvm来说命令的输出就是jvm的输入
            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            String line;
            System.out.println("<OUTPUT>");
            while ( (line = br.readLine()) != null)
                System.out.println(line);
            System.out.println("</OUTPUT>");
            int exitVal = proc.waitFor();            
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t)
          {
            t.printStackTrace();
          }
    }
}

java BadExecWinDir
java.io.IOException: CreateProcess: dir error=2
        at java.lang.Win32Process.create(Native Method)
        at java.lang.Win32Process.<init>(Unknown Source)
        at java.lang.Runtime.execInternal(Native Method)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at BadExecWinDir.main(BadExecWinDir.java:12)
That's because the directory command is part of the Windows command interpreter and not a separate executable
To run the Windows command interpreter, execute either command.com or cmd.exe, depending on the Windows operating system you use.

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

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();  
              }
    }
}

public class GoodWindowsExec
{
    public static void main(String args[])
    {
        if (args.length < 1)
        {
            System.out.println("USAGE: java GoodWindowsExec <cmd>");
            System.exit(1);
        }
        
        try
        {            
            String osName = System.getProperty("os.name" );
            String[] cmd = new String[3];

            if( osName.equals( "Windows NT" ) )
            {
                cmd[0] = "cmd.exe" ;
                cmd[1] = "/C" ;
                cmd[2] = args[0];
            }
            else if( osName.equals( "Windows 95" ) )
            {
                cmd[0] = "command.com" ;
                cmd[1] = "/C" ;
                cmd[2] = args[0];
            }
            
            Runtime rt = Runtime.getRuntime();
            System.out.println("Execing " + 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);        
        } catch (Throwable t)
          {
            t.printStackTrace();
          }
    }
}

java GoodWindowsExec "dir *.java"
Running GoodWindowsExec with any associated document type will launch the application associated with that document type.
 For example, to launch Microsoft Word to display a Word document (i.e., one with a .doc extension), type: 

>java GoodWindowsExec "yourdoc.doc"
Thus, to avoid the third pitfall related to Runtime.exec(), do not assume that a command is an executable program; know whether you are executing a standalone executable or an interpreted command
It is important to note that the method used to obtain a process's output stream is called getInputStream(). The thing to remember is that the API sees things from the perspective of the Java program and not the external process. Therefore, the external program's output is the Java program's input. And that logic carries over to the external program's input stream, which is an output stream to the Java program. 

4.Runtime.exec() is not a command line One final pitfall to cover with Runtime.exec() is mistakenly assuming that exec() accepts any String that your command line (or shell) accepts. Runtime.exec() is much more limited and not cross-platform

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

// StreamGobbler omitted for brevity

public class BadWinRedirect
{
    public static void main(String args[])
    {
        try
        {            
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("java jecho 'Hello World' > test.txt");
            // 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);        
        } catch (Throwable t)
          {
            t.printStackTrace();
          }
    }
}
java BadWinRedirect
OUTPUT>'Hello World' > test.txt
ExitValue: 0
The program BadWinRedirect attempted to redirect the output of an echo program's simple Java version into the file test.txt. However, we find that the file test.txt does not exist. The jecho program simply takes its command-line arguments and writes them to the standard output stream. 
Instead, exec() executes a single executable (a program or script). If you want to process the stream to either redirect it or pipe it into another program, you must do so programmatically, using the java.io package.
import java.util.*;
import java.io.*;

class StreamGobbler extends Thread
{
    InputStream is;
    String type;
    OutputStream os;
    
    StreamGobbler(InputStream is, String type)
    {
        this(is, type, null);
    }

    StreamGobbler(InputStream is, String type, OutputStream redirect)
    {
        this.is = is;
        this.type = type;
        this.os = redirect;
    }
    
    public void run()
    {
        try
        {
            PrintWriter pw = null;
            if (os != null)
                pw = new PrintWriter(os);
                
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
            {
                if (pw != null)
                    pw.println(line);
                System.out.println(type + ">" + line);    
            }
            if (pw != null)
                pw.flush();
        } catch (IOException ioe)
            {
            ioe.printStackTrace();  
            }
    }
}

public class GoodWinRedirect
{
    public static void main(String args[])
    {
        if (args.length < 1)
        {
            System.out.println("USAGE java GoodWinRedirect <outputfile>");
            System.exit(1);
        }
        
        try
        {            
            FileOutputStream fos = new FileOutputStream(args[0]);
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("java jecho 'Hello World'");
            // any error message?
            StreamGobbler errorGobbler = new 
                StreamGobbler(proc.getErrorStream(), "ERROR");            
            
            // any output?
            StreamGobbler outputGobbler = new 
                StreamGobbler(proc.getInputStream(), "OUTPUT", fos);
                
            // kick them off
            errorGobbler.start();
            outputGobbler.start();
                                    
            // any error???
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);
            fos.flush();
            fos.close();        
        } catch (Throwable t)
          {
            t.printStackTrace();
          }
    }
}

java GoodWinRedirect test.txt
The solution to the pitfall was to simply control the redirection by handling the external process's standard output stream separately from the Runtime.exec() method. 
before finalizing arguments to Runtime.exec() and writing the code, quickly test the arguments. Listing 4.8 is a simple command-line utility that allows you to do just that. 

 

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

// class StreamGobbler omitted for brevity

public class TestExec
{
    public static void main(String args[])
    {
        if (args.length < 1)
        {
            System.out.println("USAGE: java TestExec \"cmd\"");
            System.exit(1);
        }
        
        try
        {
            String cmd = args[0];
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd);
            
            // any error message?
            StreamGobbler errorGobbler = new 
                StreamGobbler(proc.getErrorStream(), "ERR");            
            
            // any output?
            StreamGobbler outputGobbler = new 
                StreamGobbler(proc.getInputStream(), "OUT");
                
            // kick them off
            errorGobbler.start();
            outputGobbler.start();
                                    
            // any error???
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);
        } catch (Throwable t)
          {
            t.printStackTrace();
          }
    }
}

 

java TestExec "explorer.exe aa.html"
To sum up, follow these rules of thumb to avoid the pitfalls in Runtime.exec(): 
1.      You cannot obtain an exit status from an external process until it has exited 
2.      You must immediately handle the input, output, and error streams from your spawned external process 
3.      You must use Runtime.exec() to execute programs 
4.      You cannot use Runtime.exec() like a command line 

 

http://web4.blog.163.com/blog/static/1896941312009124102715446/

http://tech.it168.com/j/2006-04-29/200604291539038.shtml

 

Runtime.exec() 不等同于直接执行command line命令!

Runtime.exec()很有局限性,对有些命令不能直接把command line里的内容当作String参数传给exec().

比如重定向等命令。举个例子:

javap -l xxx > output.txt

这时要用到exec的第二种重载,即input 参数为String[]:

Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","javap -l xxx > output.txt"});

rm -rf name*

Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","rm -rf name*"});

 

http://www.cnblogs.com/rspb/p/4648917.html

 

Runtime 封装着java程序的运行时环境。通过Runtime实例,java应用能够与其运行的环境连接。Runtime在jvm中保持一个单例,所以不能通过Runtime类的构造函数。只能通过Runtime.getRuntime()来获的当前Runtime的一个实例。获得Runtime实例后,就可以通过Runtime的exec()方法在当前jvm进程外启动其他进程了。很常见的一个应用就是,启动浏览器进程来显示一个程序的帮助页面。

在Runtime类中存在四个exec()重载方法.

Java代码 收藏代码
  1. public Process exec(String command);
  2. public Process exec(String [] cmdArray);
  3. public Process exec(String command, String [] envp);
  4. public Process exec(String [] cmdArray, String [] envp);


主要参数是要启动进程的名称,以及启动该进程时需要的参数。然后是一些环境相关的属性。envp是已name=value,
形式传入的。具体查看下源码便一目了然了。

通常,启动另外一个进程后,需要获取另外一个进程的执行结果,然后根据结果执行后续的流程。要获取外部进程的运行结果,可以调用Process的exitValue() 方法。下面代码中启动一个java编译器进程。

Java代码 收藏代码
  1. try {
  2. Runtime rt = Runtime.getRuntime();
  3. Process proc = rt.exec("javac");
  4. int exitVal = proc.exitValue();
  5. System.out.println("Process exitValue: " + exitVal);
  6. } catch (Throwable t) {
  7. t.printStackTrace();
  8. }


不幸的是,你将看到下面的结果:
java.lang.IllegalThreadStateException: process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at com.test.runtime.Test.BadExecJavac(Test.java:13)
at com.test.runtime.Test.main(Test.java:5)

原因是exitValue()方法并不会等待外部进程结束。如果外部进程还未结束,exitValue()将会抛出IllegalThreadStateException。解决办法就是调用Process的waitfor()方法。waitfor()方法会挂起当前线程,一直等到外部进程结束。当然使用exitValue()或者waitfor()完全取决你的需求。可以设个boolean标志,来确定使用哪个。运行下面的代码:

Java代码 收藏代码
  1. try {
  2. Runtime rt = Runtime.getRuntime();
  3. Process proc = rt.exec("javac");
  4. int exitVal = proc.waitFor();
  5. System.out.println("Process exitValue: " + exitVal);
  6. } catch (Throwable t) {
  7. t.printStackTrace();
  8. }


发现程序被阻塞了,什么原因呢?JDK's Javadoc文档解释说:
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
翻译:
一些平台只为标准输入输出提供有限的缓存。错误的写子进程的输入流或者错误的都子进程的输出流都有可能造成子进程的阻塞,甚至是死锁。

解决上面问题的办法就是程序中将子进程的输出流和错误流都输出到标准输出中。

Java代码 收藏代码
  1. try {
  2. Runtime rt = Runtime.getRuntime();
  3. Process proc = rt.exec("javac");
  4. InputStream stderr = proc.getErrorStream();
  5. InputStreamReader isr = new InputStreamReader(stderr);
  6. BufferedReader br = new BufferedReader(isr);
  7. String line = null;
  8. System.out.println("<ERROR>");
  9. while ((line = br.readLine()) != null)
  10. System.out.println(line);
  11. System.out.println("</ERROR>");
  12. int exitVal = proc.waitFor();
  13. System.out.println("Process exitValue: " + exitVal);
  14. } catch (Throwable t) {
  15. t.printStackTrace();
  16. }


上面的代码中仅仅是输出了错误流,并没有输出子进程的输出流。在程序中最好是能将子进程的错误流和输出流都能输出并清空。

在windows系统中,很多人会利用Runtime.exec()来调用不可执行的命令。例如dir和copy;

Java代码 收藏代码
  1. try {
  2. Runtime rt = Runtime.getRuntime();
  3. Process proc = rt.exec("dir");
  4. InputStream stdin = proc.getInputStream();
  5. InputStreamReader isr = new InputStreamReader(stdin);
  6. BufferedReader br = new BufferedReader(isr);
  7. String line = null;
  8. System.out.println("<OUTPUT>");
  9. while ((line = br.readLine()) != null)
  10. System.out.println(line);
  11. System.out.println("</OUTPUT>");
  12. int exitVal = proc.waitFor();
  13. System.out.println("Process exitValue: " + exitVal);
  14. } catch (Throwable t) {
  15. t.printStackTrace();
  16. }


运行上面的代码,将会得到一个错误代码为2的错误。在win32系统中,error=2表示文件未找到。也就是不存在dir.exe和copy.exe。这是因为dir命令式windows中命令行解析器的一部分,并不是单独的一个可执行的命令。要运行上面的命令,得先启动windows下的命令行解析器command.com或者cmd.exe,这个取决于windows的系统的版本。

Java代码 收藏代码
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. class StreamGobbler extends Thread {
  6. InputStream is;
  7. String type;
  8. StreamGobbler(InputStream is, String type) {
  9. this.is = is;
  10. this.type = type;
  11. }
  12. public void run() {
  13. try {
  14. InputStreamReader isr = new InputStreamReader(is);
  15. BufferedReader br = new BufferedReader(isr);
  16. String line = null;
  17. while ((line = br.readLine()) != null)
  18. System.out.println(type + ">" + line);
  19. } catch (IOException ioe) {
  20. ioe.printStackTrace();
  21. }
  22. }
  23. }
  24. public class GoodWindowsExec {
  25. public static void main(String args[]) {
  26. if (args.length < 1) {
  27. System.out.println("USAGE: java GoodWindowsExec <cmd>");
  28. System.exit(1);
  29. }
  30. try {
  31. String osName = System.getProperty("os.name");
  32. String[] cmd = new String[3];
  33. if (osName.equals("Windows NT")) {
  34. cmd[0] = "cmd.exe";
  35. cmd[1] = "/C";
  36. cmd[2] = args[0];
  37. } else if (osName.equals("Windows 95")) {
  38. cmd[0] = "command.com";
  39. cmd[1] = "/C";
  40. cmd[2] = args[0];
  41. }
  42. Runtime rt = Runtime.getRuntime();
  43. System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
  44. Process proc = rt.exec(cmd);
  45. StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
  46. StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
  47. errorGobbler.start();
  48. outputGobbler.start();
  49. int exitVal = proc.waitFor();
  50. System.out.println("ExitValue: " + exitVal);
  51. } catch (Throwable t) {
  52. t.printStackTrace();
  53. }
  54. }
  55. }


另外,Runtime.exec()并不是命令解析器,这是启动某个进程。并不能执行一些命令行的命令。下面是一个常见的错误:

Java代码 收藏代码
  1. try {
  2. Runtime rt = Runtime.getRuntime();
  3. Process proc = rt.exec("java jecho 'Hello World' > test.txt");
  4. StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
  5. StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
  6. errorGobbler.start();
  7. outputGobbler.start();
  8. int exitVal = proc.waitFor();
  9. System.out.println("ExitValue: " + exitVal);
  10. } catch (Throwable t) {
  11. t.printStackTrace();
  12. }


上面的代码希望像DOS系统中一样将命令的执行结果输出到文件中去。但是Runtime.exec()并不是命令行解析器。要想重定向输出流,必须在程序中编码实现。

Java代码 收藏代码
    1. import java.util.*;
    2. import java.io.*;
    3. class StreamGobbler extends Thread {
    4. InputStream is;
    5. String type;
    6. OutputStream os;
    7. StreamGobbler(InputStream is, String type) {
    8. this(is, type, null);
    9. }
    10. StreamGobbler(InputStream is, String type, OutputStream redirect) {
    11. this.is = is;
    12. this.type = type;
    13. this.os = redirect;
    14. }
    15. public void run() {
    16. try {
    17. PrintWriter pw = null;
    18. if (os != null)
    19. pw = new PrintWriter(os);
    20. InputStreamReader isr = new InputStreamReader(is);
    21. BufferedReader br = new BufferedReader(isr);
    22. String line = null;
    23. while ((line = br.readLine()) != null) {
    24. if (pw != null)
    25. pw.println(line);
    26. System.out.println(type + ">" + line);
    27. }
    28. if (pw != null)
    29. pw.flush();
    30. } catch (IOException ioe) {
    31. ioe.printStackTrace();
    32. }
    33. }
    34. }
    35. public class GoodWinRedirect {
    36. public static void main(String args[]) {
    37. if (args.length < 1) {
    38. System.out.println("USAGE java GoodWinRedirect <outputfile>");
    39. System.exit(1);
    40. }
    41. try {
    42. FileOutputStream fos = new FileOutputStream(args[0]);
    43. Runtime rt = Runtime.getRuntime();
    44. Process proc = rt.exec("java jecho 'Hello World'");
    45. StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
    46. StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", fos);
    47. errorGobbler.start();
    48. outputGobbler.start();
    49. int exitVal = proc.waitFor();
    50. System.out.println("ExitValue: " + exitVal);
    51. fos.flush();
    52. fos.close();
    53. } catch (Throwable t) {
    54. t.printStackTrace();
    55. }
    56. }
    57. }  

 

http://www.cnblogs.com/nkxyf/archive/2012/12/13/2815978.html

 

posted @ 2015-02-12 10:51  沧海一滴  阅读(9372)  评论(0编辑  收藏  举报