17.3 Writing files

To write messages to the file system you can use a FileWritingMessageHandler. This class can deal with File, String, or byte array payloads. In its simplest form the FileWritingMessageHandler only requires a destination directory for writing the files. The name of the file to be written is determined by the handler's FileNameGenerator. The default implementation looks for a Message header whose key matches the constant defined as FileHeaders.FILENAME.

Additionally, you can configure the encoding and the charset that will be used in case of a String payload.

To make things easier you can configure the FileWritingMessageHandler as part of an outbound channel adapter using the namespace.

 <file:outbound-channel-adapter id="filesOut" directory="file:${input.directory.property}"/>

The namespace based configuration also supports a delete-source-files attribute. If set to true, it will trigger deletion of the original source files after writing to a destination. The default value for that flag is false.

 <file:outbound-channel-adapter id="filesOut"
             directory="file:${output.directory}" 
             delete-source-files="true"/>

[Note]Note

The delete-source-files attribute will only have an effect if the inbound Message has a File payload or if the FileHeaders.ORIGINAL_FILE header value contains either the source File instance or a String representing the original file path.

In cases where you want to continue processing messages based on the written File you can use the outbound-gateway instead. It plays a very similar role as the outbound-channel-adapter. However after writing the File, it will also send it to the reply channel as the payload of a Message.

 <file:outbound-gateway id="mover" request-channel="moveInput" 
            reply-channel="output"
            directory="${output.directory}" 
            delete-source-files="true"/>

[Note]Note
The 'outbound-gateway' works well in cases where you want to first move a File and then send it through a processing pipeline. In such cases, you may connect the file namespace's 'inbound-channel-adapter' element to the 'outbound-gateway' and then connect that gateway's reply-channel to the beginning of the pipeline.

If you have more elaborate requirements or need to support additional payload types as input to be converted to file content you could extend the FileWritingMessageHandler, but a much better option is to rely on a Transformer.