【问题标题】:Use shell Command in Spring Batch SystemCommandTasklet在 Spring Batch SystemCommandTasklet 中使用 shell 命令
【发布时间】:2020-06-11 21:09:55
【问题描述】:

我想在 spring 批处理 systemCommandTasklet 中运行这个命令,但它不起作用。

 tail -1 file1.txt > input_footer.txt && head -n -1 file1.txt > input_body.txt

代码:

        String Commmand = String.format("tail -1 %s > input_footer.txt && head -n -1 %s > input_body.txt", fileName.getFilename(),fileName.getFilename());

        systemCommandTasklet.setCommand(Commmand);

        systemCommandTasklet.setWorkingDirectory(woringDir);
        systemCommandTasklet.setTimeout(10000);
        systemCommandTasklet.setInterruptOnCancel(true);

没有生成输出文件。

有什么解决方法吗? 基本上我想第一步将正文和页脚分成两个文件。

【问题讨论】:

  • 我不确定这个问题与 javaspring 有何关系。 headtail 默认打印 10 行,这里你指定了 1。
  • 抱歉,更新了问题

标签: java spring spring-boot spring-batch


【解决方案1】:

我通过使用 ProcessBuilder 和 MethodInvokingTaskletAdapter 解决了这个问题

public ExitStatus processFile(String fileName, String workingDir) throws InterruptedException, IOException {

        boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
        logger.info("OS windows {} :", isWindows);
        String command = String.format("tail -1 %s > input_footer.txt && head -n -1 %s > input_body.txt", fileName, fileName);
        logger.info("command {} and working dir{} :", command, workingDir);
        ProcessBuilder builder = new ProcessBuilder();

        builder.command(bashPath, "-c", command);
        builder.directory(new File(workingDir));
        Process process = builder.start();
        StreamGobbler streamGobbler =
                new StreamGobbler(process.getInputStream(), System.out::println);
        Executors.newSingleThreadExecutor().submit(streamGobbler);
        int exitCode = process.waitFor();
        ExitStatus status = exitCode == 0 ? ExitStatus.COMPLETED : ExitStatus.FAILED;

        return status;
    }

 public MethodInvokingTaskletAdapter preProcessFileAdapter(@Value("#{jobExecutionContext['customerFile']}") String file, PreProcessFile preProcessFile)
    {
        String workingDir = FilenameUtils.getFullPath(file);
        String fileName = FilenameUtils.getName(file);

        MethodInvokingTaskletAdapter methodInvokingTaskletAdapter=new MethodInvokingTaskletAdapter();
        methodInvokingTaskletAdapter.setTargetObject(preProcessFile);
        methodInvokingTaskletAdapter.setTargetMethod("processFile");
        methodInvokingTaskletAdapter.setArguments(new String[]{fileName,workingDir});



 return methodInvokingTaskletAdapter;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-26
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2019-08-05
    • 2019-02-10
    • 1970-01-01
    相关资源
    最近更新 更多