1

我有一个可以编译和运行其他 Java 程序的 Java 程序。我也有 .txt 文件,这些文件具有输入到其他 Java 程序的输入。

我想知道如何捕获使用这些输入文件运行的输出?

4

2 回答 2

4

我假设您通过 ProcessBuilder 或 Runtime.exec() 调用另一个程序都返回一个 Process 对象,该对象具有方法 getInputStream() 和 getErrorStream() 允许您监听输出和错误(stdout,stderr)其他进程的流。

考虑以下代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {

    public static void main(String[] args){
        Test t = new Test();

        t.start();
    }

    private void start(){
        String command = //Command to invoke the program

        ProcessBuilder pb = new ProcessBuilder(command);

        try{
            Process p = pb.start();

            InputStream stdout = p.getInputStream();
            InputStream stderr = p.getErrorStream();

            StreamListener stdoutReader = new StreamListener(stdout);
            StreamListener stderrReader = new StreamListener(stderr);

            Thread t_stdoutReader = new Thread(stdoutReader);
            Thread t_stderrReader = new Thread(stderrReader);

            t_stdoutReader.start();
            t_stderrReader.start();
        }catch(IOException n){
            System.err.println("I/O Exception: " + n.getLocalizedMessage());
        }
    }

    private class StreamListener implements Runnable{
        private BufferedReader Reader;
        private boolean Run;

        public StreamListener(InputStream s){
            Reader = new BufferedReader(new InputStreamReader(s));
            Run = true;
        }

        public void run(){
            String line;

            try{
                while(Run && (line = Reader.readLine()) != null){
                    //At this point, a line of the output from the external process has been grabbed. Process it however you want.
                    System.out.println("External Process: " + line);
                }
            }catch(IOException n){
                System.err.println("StreamListener I/O Exception!");
            }
        }
    }
}
于 2013-10-08T04:10:08.390 回答
0

掌握这个例子:

  // Try these charsets for encoding text file
  String[] csStrs = {"UTF-8", "UTF-16BE", "UTF-16LE", "UTF-16", "GB2312", "GBK", "BIG5"};
  String outFileExt = "-out.txt";   // Output filenames are "charset-out.txt"

  // Write text file in the specified file encoding charset
  for (int i = 0; i < csStrs.length; ++i) {
     try (OutputStreamWriter out =
             new OutputStreamWriter(
                new FileOutputStream(csStrs[i] + outFileExt), csStrs[i]);
          BufferedWriter bufOut = new BufferedWriter(out)) {  // Buffered for efficiency
        System.out.println(out.getEncoding());  // Print file encoding charset
        bufOut.write(message);
        bufOut.flush();
     } catch (IOException ex) {
        ex.printStackTrace();
     }
  }

  // Read raw bytes from various encoded files
  //   to check how the characters were encoded.
  for (int i = 0; i < csStrs.length; ++i) {
     try (BufferedInputStream in = new BufferedInputStream(  // Buffered for efficiency
             new FileInputStream(csStrs[i] + outFileExt))) {
        System.out.printf("%10s", csStrs[i]);    // Print file encoding charset
        int inByte;
        while ((inByte = in.read()) != -1) {
           System.out.printf("%02X ", inByte);   // Print Hex codes
        }
        System.out.println();
     } catch (IOException ex) {
        ex.printStackTrace();
     }
  }

  // Read text file with character-stream specifying its encoding.
  // The char will be translated from its file encoding charset to
  //   Java internal UCS-2.
  for (int i = 0; i < csStrs.length; ++i) {
     try (InputStreamReader in =
             new InputStreamReader(
                new FileInputStream(csStrs[i] + outFileExt), csStrs[i]);
          BufferedReader bufIn = new BufferedReader(in)) {  // Buffered for efficiency
        System.out.println(in.getEncoding());  // print file encoding charset
        int inChar;
        int count = 0;
        while ((inChar = in.read()) != -1) {
           ++count;
           System.out.printf("[%d]'%c'(%04X) ", count, (char)inChar, inChar);
        }
     System.out.println();
     } catch (IOException ex) {
        ex.printStackTrace();
     }
  }

} }

于 2013-10-08T04:09:19.963 回答