我想在Java中使用awk命令行。为此,我有以下代码(我在教程中看到了此代码):

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


在此示例中,我的代码显示了文件的第一列。

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


我想将输出打印在文件中,但无法弄清楚。

最佳答案

通常,要在Java中以编程方式运行awk命令,可以使用Jawk。我需要自己构建它,但没什么大不了的。我已经用1.03版进行了测试,可以针对我的用例以编程方式调用awk命令,如下所示。

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


您可能需要在类路径中添加slf4j.jar,而jawk.jar在内部需要。

10-07 13:42