Java中的awk命令 [英] awk commands in Java
本文介绍了Java中的awk命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Java中使用awk命令行.为此,我有以下代码(我在教程中看到了此代码):
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.
推荐答案
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();
您可能需要在sawk.jar内部所需的类路径中添加slf4j.jar.
You may be required to add slf4j.jar in classpath which is required by the jawk.jar internally.
这篇关于Java中的awk命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文