繁体   English   中英

如何从 java 运行外部可执行文件并将 output 保存在 txt

[英]How to run external executable from java and save the output in txt

hi i new in java and i try to run executable (exe) of vienna packge from eclipse java, i want it will get string and use this on the exe, and i want to save the output of the exe in txt file, how can我做吗?

    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

Runtime.getRuntim().exec(...); 返回 Process 的一个实例。 Process 有一个方法getOutputStream 使用此方法获取 stream。 读取 stream 后。

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

您可以使用ProcessBuilder.redirectOutput直接写入文件,例如。

import java.io.File;

public class Sample {
  private static final String EXE_FOLDER = "C:\\Program Files (x86)\\ViennaRNA Package";
  private static final String EXE_NAME = "RNAup.exe";

  public static void main(String[] args) throws Exception {
    File exeDir = new File(EXE_FOLDER);
    File exeFile = exeDir.toPath().resolve(EXE_NAME).toFile();
    File outFile = new File("out.txt");
    File errFile = new File("err.txt");

    System.out.println("exeDir="+exeDir);
    System.out.println("exeFile="+exeFile);
    System.out.println("outFile="+outFile.getAbsolutePath());
    System.out.println("errFile="+errFile.getAbsolutePath());

    String[] params = { exeFile.getAbsolutePath() , "GHHI" };
    ProcessBuilder proc = new ProcessBuilder(params).directory(exeDir);

    proc.redirectOutput(outFile);
    proc.redirectError(errFile);
    proc.start();
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM