How can I execute unix sort command (/usr/bin/sort) from Java

How can I execute unix sort command (/usr/bin/sort) from Java


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
String whatever = "filename";
Process p = Runtime.getRuntime().exec("sort -t -k2 2 -k1 1 " + whatever);

No comments:

Post a Comment