2

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 "";
}

1 Comment

Thanks for your response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.