如何在ProcessBuilder中将文件的内容作为参数传递

时间:2012-10-08 11:10:47

标签: java parameter-passing processbuilder

我想将.dat文件的内容作为ProcessBuilder中的参数传递。我该怎么做?

.dat文件包含:

08/10/12 4546.4 4644.5 6465.4 3 6.546 core dia,WH,C/C,no of steps,SF 0054.0 0005.0 005.00 0006.0 0006.0 066.00 0006.0 0006.0 006.00 leg width,yoke width,1/2 section step thk-Biggest size

我想将该文件的内容作为参数传递给以下代码

 ProcessBuilder processBuilder = new ProcessBuilder("E:\\MyFile.exe");

1 个答案:

答案 0 :(得分:1)

FileReader r = null;
try {
    r = new FileReader(pathToDatFile);
    char[] buf = new char[50000]; // Or whatever is a good max length.
    int len = r.read(buf);
    String content = new String(buf, 0, len);
    String[] params = content.split(" ");
    ArrayList<String> invocation = new ArrayList<String>();
    invocation.add("E:\\MyFile.exe");
    invocation.addAll(Arrays.asList(params));
    ProcessBuilder processBuilder = new ProcessBuilder(invocation);
} catch (Exception e) {
    // handle me!
} finally {
   try { r.close(); } catch (Exception e) { /* handle me! */ }
}

另外:你的.dat文件是什么编码的?如果它不是ASCII,你必须通过FileInputStream - &gt; InputStreamReader,因此您可以在InputStreamReader中设置正确的编码。否则,您的代码将使用它碰巧运行的计算机上的默认值,结果会产生令人惊讶的不一致!