繁体   English   中英

如何从Java执行Unix排序命令(/ usr / bin / sort)?

[英]How can I execute unix sort command (/usr/bin/sort) from Java?

我希望利用unix sort命令对Java中的大型文本文件进行排序。 我尝试用流程生成器执行排序,但是没有运气。 但是,当我打印确切的命令时,它将执行并将其复制并粘贴到终端中,效果很好。

到目前为止,我已经尝试使用/ bin / sh -c“”执行,确保输入文件所在的目录以及输出文件将被完全允许的位置(chmod 777),但是没有运气。

这是代码(如果看起来很有趣,请注意正在使用Guava中的一些函数)

File inputFile = new File(inputFileName);

//build the command (optional number of sort columns)
List<String> command = new LinkedList<String>();
command.addAll(ImmutableList.<String>of("sort","-t"+delimiter));
for (int i : sortFieldPositions) {
    command.add("-k"+i+","+i);
}
command.addAll(ImmutableList.<String>of(inputFileName,">",outputFileName));

//for debugging: output the command that will be executed
System.out.println("Executing: "+Joiner.on(" ").join(command));

//construct and start the process
Process process = new ProcessBuilder(command).redirectErrorStream(true).directory(inputFile.getParentFile()).start();
//for debugging: save process output
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder outputStringBuilder = new StringBuilder();
for (String line; (line = bufferedReader.readLine()) != null; /*reading taking place in check */) {
    System.out.println("FROM PROCESS: "+line);
    outputStringBuilder.append(line);
}
bufferedReader.close();

if (process.exitValue() != 0) {
    //something went wrong
    throw new RuntimeException("Error code "+process.exitValue()+" executing command: "+Joiner.on(" ").join(command)+"\n"+outputStringBuilder.toString());
}

不幸的是,这不起作用,并显示以下输出:

Executing: sort -t, -k2,2 -k1,1 /tmp/java/TestDataSorterImporterInput.txt /tmp/java/TestDataSorterImporterOutput.txt
FROM PROCESS: sort: stat failed: >: No such file or directory

编辑:最好注意一下,如果我从命令中删除了保存输出(> outputfile),那么该命令将在没有投诉的情况下执行,并且已排序的版本将出现在Processes输入流的输出中)

外壳程序知道如何执行输出重定向。 排序程序无法自行执行。 因此,如果要重定向,则需要执行/bin/sh -c ...使其进入循环。

(您写道您已经尝试过此方法,但是那一定有其他问题)。

流程= new ProcessBuilder(“ / bin / bash”,“ -c”,“ sort -t'|'-k2”)。start();

尝试这个:

String whatever = "filename";
Process p = Runtime.getRuntime().exec("sort -t -k2 2 -k1 1 " + whatever);

看到这个网站。

暂无
暂无

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

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