首页 > 解决方案 > 如何从java运行外部可执行文件并将输出保存在txt中

问题描述

嗨,我是 java 新手,我尝试从 eclipse java 运行 vienna packge 的可执行文件(exe),我希望它会获取字符串并在 exe 上使用它,我想将 exe 的输出保存在 txt 文件中,如何我做吗?

    String[] params = new String [2];
    params[0] = "C:\\Program Files (x86)\\ViennaRNA Package\\RNAup.exe";
    params[1] = "GHHI";   
    try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
        out.print(Runtime.getRuntime().exec(params));
    }

tnx

标签: javaeclipsefileexe

解决方案


Runtime.getRuntim().exec(...);返回 Process 的一个实例。过程有方法getOutputStream。使用此方法获取流。一旦你从它读取流。

import java.io.*;

public class Main {
    public static void main(String[] args) {
        String[] params = new String[2];
        params[0] = "C:\\Program Files (x86)\\ViennaRNA Package\\RNAup.exe";
params[1] = "GHHI";
        try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
            Process p = Runtime.getRuntime().exec(params);
            final InputStream inputStream = p.getInputStream();
            final BufferedInputStream bis = new BufferedInputStream(inputStream);
            final BufferedReader br = new BufferedReader(new InputStreamReader(bis));
            String line;
            while((line = br.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

推荐阅读