1

I want to use awk command line in Java. For that, I have this code (I saw this code in a tutorial):

Map map = new HashMap();
map.put("file", new File(fileDirectory)); 

CommandLine cmdLine = new CommandLine("awk"); 
cmdLine.addArgument("{print $1}", false); 
cmdLine.addArgument("${file}"); 
cmdLine.setSubstitutionMap(map);
System.out.println(cmdLine.toString()); 

DefaultExecuteResultHandler resultHandler = new   DefaultExecuteResultHandler();  
ExecuteWatchdog watchdog = new ExecuteWatchdog(10000); 
DefaultExecutor executor = new DefaultExecutor(); 
executor.setWatchdog(watchdog); 
executor.execute(cmdLine, resultHandler); 

resultHandler.waitFor(); 

In this example my code prints the first column of the file.

10
10
10
10
10
10
10
10
10
10
10
10
10
10
10

I want to print the output in a file but I can't figure it out.

diborbi
  • 83
  • 2
  • 10
  • 5
    This seems like an XY Problem. Java has all the tools necessary for reading a file and extracting the first token from each line – Reimeus Sep 09 '16 at 15:28
  • Possible duplicate of [Executing awk command in java](https://stackoverflow.com/questions/26211696/executing-awk-command-in-java) – Michael Peyper May 31 '17 at 10:33

2 Answers2

0

In general to run awk command programmatically in Java you can use Jawk. I was required to build it myself but not a big deal. I have tested with version 1.03 to programmatically call the awk command like below for my use-case.

            String[] awkArgs= { "-f", awkProgramPath };
            // Create a stream to hold the output
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            // Tell Java to use your byte arrya output stream temporarily
            System.setOut(ps);

            AwkParameters parameters = new AwkParameters(Main.class, null);
            AwkSettings settings = parameters.parseCommandLineArguments(awkArgs);

            //Instead of passing file as argument setting the file content as input. 
            //This is done to adapt the line delimiters in file content to the specific OS. Otherwise Jawk fails in splitting the lines.
            //If it is not required, this step cab be skipped and the input file path can be passed as additional argument
            String inputFileContent = new String(Files.readAllBytes(inputFile.toPath())); 
            //Adapting line delimiter.
            inputFileContent = inputFileContent.replaceAll("[\r]?\n", System.getProperty("line.separator"));
            settings.setInput(new ByteArrayInputStream(inputFileContent.getBytes()));

            //Invoking the awk command
            Awk awk = new Awk();
            awk.invoke(settings);
            //Set the old print stream back. May be you can do it in try..finally block to be failsafe.
            System.setOut(sysout);
            //Get the output from byte array output stream
            String output = baos.toString();

You may be required to add slf4j.jar in classpath which is required by the jawk.jar internally.

Loganathan
  • 903
  • 2
  • 10
  • 23
-1

I have never used DefaultExecutor but you could do it like below

Process process = Runtime.getRuntime().exec(cmdLine.toString());
InputStream stdout = process.getInputStream();

BufferedReader stdout_br = new BufferedReader(new InputStreamReader(stdout));
String tmp;
StringBuilder cmp_stb = new StringBuilder();
while ((tmp = stdout_br.readLine()) != null) {
   cmp_stb.append(tmp + "\n");
}
stdout_br.close();

Save the string to a file.
Alternatively, since you're just supplying a string command, you could also append a file redirection like ">filename" to the command and execute.

DebD
  • 373
  • 3
  • 20
  • I am trying not to use getRuntime().exec() because of some comments that I read about that command. – diborbi Sep 12 '16 at 16:51