Spring Batch - 从远程位置复制文件

时间:2014-11-17 15:38:09

标签: spring spring-batch file-copying

我是Spring批次的新手。我需要实现以下目标: 步骤1:将文件从远程位置复制到本地目录。 第2步:处理文件的每一行。 第3步:将处理过的行存储到数据库中。

我确信最后两步,但我怎样才能实现第一步?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你可以编写一个tasklet来实现这个,这个tasklet将分开进行

<step id="movingFile" next="step2">
        <tasklet ref="voterImportFileMovingTasklet" />
        <listeners>
            <listener ref="stepLevelListener" />
        </listeners>
    </step>
<step id="step2" >
            <chunk reader="FileReader" processor="ItemProcessor" writer="ItemWriter" commit-interval="300"
                skip-limit="1000">
                <skippable-exception-classes>
                    <include class="java.lang.Exception" />
                    </skippable-exception-classes>
                <listeners>
                    <listener ref="voterImportListener" />
                </listeners>
            </chunk>
    </step>

Tasklet将是

public class FileMovingTasklet implements Tasklet, InitializingBean {
private Resource sourceDirectory;
private Resource targetDirectory;



private static final Log LOG = LogFactory.getLog(FileMovingTasklet.class);

public Resource getSourceDirectory() {
    return sourceDirectory;
}

public void setSourceDirectory(Resource sourceDirectory) {
    this.sourceDirectory = sourceDirectory;
}

public Resource getTargetDirectory() {
    return targetDirectory;
}

public void setTargetDirectory(Resource targetDirectory) {
    this.targetDirectory = targetDirectory;
}


@Override
public void afterPropertiesSet() throws Exception {
    Assert.notNull(sourceDirectory, "Source directory must be set");
    Assert.notNull(targetDirectory, "Target directory must be set");
}

@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

    InputStream inStream = null;
    OutputStream outStream = null;
    File[] files;
    File dir = sourceDirectory.getFile();
    Assert.state(dir.isDirectory());
        files = dir.listFiles();
    File bfile = null;
    for (int i = 0; i < files.length; i++) {


            bfile = new File(targetDirectory.getURL().getPath() + File.separator + files[i].getName());

        inStream = new FileInputStream(files[i]);
        outStream = new FileOutputStream(bfile);

        byte[] buffer = new byte[1024];

        int length;
        // copy the file content in bytes
        while ((length = inStream.read(buffer)) > 0) {

            outStream.write(buffer, 0, length);

        }

        inStream.close();
        outStream.close();
    }
    return RepeatStatus.FINISHED;
}