1
votes

I have a spring batch job (defined in xml) which generates the csv export. Inside FlatFileItemWriter bean I am setting resource, where the name of file is set.

<bean id="customDataFileWriter" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
  <property name="resource" value="file:/tmp/export/custom-export.csv"/>
...

Now I need to set this file name taking account a certain logic, so I need to set the file name from some java class. Any ideas?

2

2 Answers

1
votes

Use the different builder classes of spring batch (job builder, step builder, and so on). Have a look at https://blog.codecentric.de/en/2013/06/spring-batch-2-2-javaconfig-part-1-a-comparison-to-xml/ to get an idea.

1
votes

You can implement your own FlatFileItemWriter to override the method setResource and add your own logic to rename the file.

Here's an example implementation :

@Override
public void setResource(Resource resource) {

    if (resource instanceof ClassPathResource) {

        // Convert resource
        ClassPathResource res = (ClassPathResource) resource;

        try {       

            String path = res.getPath();

            // Do something to "path" here

            File file = new File(path);  

            // Check for permissions to write
            if (file.canWrite() || file.createNewFile()) {
                file.delete();

                // Call parent setter with new resource
                super.setResource(new FileSystemResource(file.getAbsolutePath()));
                return;
            }
        } catch (IOException e) {
            // File could not be read/written
        } 
    }

    // If something went wrong or resource was delegated to MultiResourceItemWriter, 
    // call parent setter with default resource
    super.setResource(resource);
}

Another possibility exists with the use of jobParameters, if your logic can be applied before job is launched. See 5.4 Late Binding of Spring Batch Documentation.

Example :

<bean id="flatFileItemReader" scope="step"       class="org.springframework.batch.item.file.FlatFileItemReader">
    <property name="resource" value="#{jobParameters['input.file.name']}" />
</bean>

You can also use a MultiResourceItemWriter with a custom ResourceSuffixCreator. That will let you create 1 to n files with a common filename pattern.

Here's an example of the method getSuffix of a custom ResourceSuffixCreator :

@Override
public String getSuffix(int index) {

    // Your logic
    if (true)
        return "XXX" + index;
    else
        return "";
}