Spring Batch FlatFileItemWriter无法写入数据至文件问题求助
Hey there! I see you're dipping your toes into Spring Batch and hit a snag where your FlatFileItemWriter creates the file but refuses to write any actual content. Let's get this sorted out for you!
The Core Issue
The main problem in your code is the order of operations. You called writer.open() before setting up key configurations like the LineAggregator. Once open() is invoked, the writer initializes its internal state, so any settings you apply after that won't be picked up—meaning it doesn't know how to format your data for writing.
Fixed Code Example
Here's the corrected order of steps that should get your content writing properly:
// Your populated data list List<String> dataFileList = // your actual data here FlatFileItemWriter<String> writer = new FlatFileItemWriter<>(); // 1. Configure all writer properties FIRST writer.setResource(new FileSystemResource("C:\\Desktop\\test")); writer.setLineAggregator(new PassThroughLineAggregator<>()); writer.setAppendAllowed(true); // 2. Initialize the writer after configuration writer.open(new ExecutionContext()); // 3. Write your data to the file writer.write(dataFileList); // 4. Clean up resources when done writer.close();
Why This Works
Spring Batch's ItemWriter implementations follow a strict lifecycle:
- Configure first: Set all required properties (resource path, line formatter, append mode, etc.) before initializing the writer.
- Open: Initialize internal resources (like opening the file stream) once all settings are in place.
- Write: Now the writer has all the necessary rules to format and write each line from your list.
- Close: Properly shut down resources to avoid file leaks or corrupted data.
Quick Double-Checks
Just to cover all bases:
- Confirm your
dataFileListcontains non-empty strings (you mentioned it does, but it never hurts to verify). - Ensure the path
C:\\Desktop\\testhas write permissions (since the file is created, this is probably fine, but it's a common gotcha).
内容的提问来源于stack exchange,提问作者Saurabh Deshpande

