Camel Components

File

Since Camel 1.0

Both producer and consumer are supported

The File component provides access to file systems, allowing files to be processed by any other Camel Components or messages from other components to be saved to disk.

URI format

file:directoryName[?options]

Where directoryName represents the underlying file directory.

Only directories

Camel supports only endpoints configured with a starting directory. So the directoryName must be a directory. If you want to consume a single file only, you can use the fileName option, e.g., by setting fileName=thefilename. Also, the starting directory must not contain dynamic expressions with ${ } placeholders. Again use the fileName option to specify the dynamic part of the filename. The directory is fixed when the endpoint is created: to write to a dynamic directory use toD, and to read from one use pollEnrich with a simple expression (pollEnrich().simple("…​") in Java), as pollEnrich("…​") uses the uri as is.

The fileName option of a consumer is a file name, not a pattern: fileName=*.csv only consumes a file named *.csv. To consume the files that match a pattern use antInclude (wildcards such as *.csv), include (a regular expression such as .*\.csv) or includeExt (file extensions such as csv). The consumer logs a WARN when a fixed fileName has the wildcards * or ?.

The directory is a directory of the file system: file:classpath:data is a directory named classpath:data in the working directory, not a directory of the classpath. To read a classpath resource use the Language component, such as language:constant:resource:classpath:data/order.json. The file component logs a WARN when the directory starts with classpath: or resource:.

Avoid reading files currently being written by another application

Beware the JDK File IO API is a bit limited in detecting whether another application is currently writing/copying a file. And the implementation can be different depending on the OS platform as well. This could lead to that Camel thinks the file is not locked by another process and start consuming it. Therefore, you have to do your own investigation what suites your environment. To help with this Camel provides different readLock options and doneFileName option that you can use. See also Consuming files from folders where others drop files directly.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The File component supports the following options which are listed below.

Name Description Default Type

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

healthCheckConsumerEnabled (health)

Used for enabling or disabling all consumer based health checks from this component.

true

boolean

healthCheckProducerEnabled (health)

Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true.

true

boolean

Endpoint Options

The File endpoint is configured using URI syntax:

file:directoryName

With the following path and query parameters:

Path Parameters

Name Description Default Type

directoryName (common)

Required The starting directory: the consumer reads the files in it, and the producer writes the files in it (or in a subdirectory, when the file name has a path). A relative path is relative to the working directory of the JVM. The directory is fixed when the endpoint is created and cannot contain $\{ } expressions: use the fileName option for a dynamic file name.

File

Query Parameters

Name Description Default Type

charset (common)

The charset (encoding) of the file content, such as UTF-8. The consumer uses it when the file content is read as text, and the producer writes text with this charset. When writing, Camel may have to read the whole message into memory to convert it to the charset, so do not use it with big messages.

String

doneFileName (common)

The name of the done file, an empty file that marks a file as complete. Producer: after the file is written, the done file is written in the same directory. Consumer: a file is only consumed when its done file exists in the same directory, and the done file is deleted once the file is consumed (unless noop=true). The name is either a fixed name, or uses the placeholders $\{file:name} and $\{file:name.noext}, which are the only ones supported; the consumer supports the fixed part of the name either as a prefix or as a suffix, not both.

String

fileName (common)

The file name, as an expression such as the File Language. Consumer: only the file with exactly this name is consumed, as the name is not a pattern (use antInclude or include to consume the files that match a pattern); for example consume the file of today with mydata-$\{date:now:yyyyMMdd}.txt. Producer: the name of the file to write; when set, it is used instead of the CamelFileName header, unless that header holds an org.apache.camel.Expression (a String header is used as it is, not evaluated). A String value of this option is evaluated with the File Language, and an Expression object as it is. The producer also supports the CamelOverruleFileName header, which takes precedence over the CamelFileName header and is used only once, so CamelFileName does not have to be stored and restored around the producer.

String

jailStartingDirectory (common)

Used for jailing (restricting) writing files to the starting directory (and sub) only. This is enabled by default to not allow Camel to write files to outside directories (to be more secured out of the box). You can turn this off to allow writing files to directories outside the starting directory, such as parent or root folders. For consumers that use a localWorkDirectory, this also restricts the downloaded files to stay within the configured localWorkDirectory.

true

boolean

delete (consumer)

If true, the file is deleted after it is processed successfully. Cannot be combined with move.

false

boolean

moveFailed (consumer)

Sets the move failure expression based on Simple language. For example, to move files into a .error subdirectory use: .error. Note: When moving the files to the fail location Camel will handle the error and will not pick up the file again.

String

noop (consumer)

If true, the consumer leaves the file in place: it does not move or delete the file after it is processed (preMove and moveFailed still apply, and delete=true takes precedence over noop). Good for read-only data or ETL. noop=true also turns on idempotent (unless idempotent is set), so the same files are not consumed over and over again.

false

boolean

preMove (consumer)

Expression (such as File Language) used to dynamically set the filename when moving it before processing. For example to move in-progress files into the order directory set this value to order.

String

preSort (consumer)

When pre-sort is enabled then the consumer will sort the file and directory names during polling, that was retrieved from the file system. You may want to do this in case you need to operate on the files in a sorted order. The pre-sort is executed before the consumer starts to filter, and accept files to process by Camel. This option is default=false meaning disabled. The following values are supported: name (sort by file name), modified (sort by last-modified timestamp), size (sort by file size). To sort in descending (reverse) order, prefix the value with a minus sign (e.g., -modified to sort newest first). The value true is an alias for name (backward compatible).

Enum values:

  • true

  • false

  • name

  • -name

  • modified

  • -modified

  • size

  • -size

String

recursive (consumer)

Whether to also consume the files in all the subdirectories of the starting directory (see minDepth and maxDepth).

false

boolean

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

directoryMustExist (consumer (advanced))

Whether a poll fails when the starting directory does not exist (or is not a directory). By default, the poll then finds no files. Unlike startingDirectoryMustExist, which is checked when the consumer starts, this is checked on every poll.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

extendedAttributes (consumer (advanced))

A comma-separated list of file attributes that the consumer reads into the CamelFileExtendedAttributes header (a Map keyed by view:name). Each entry is a java.nio.file attribute name such as posix:permissions, posix:owner or basic:lastAccessTime. An entry view:*, such as posix:*, reads all the attributes of the view, * reads all the basic attributes, and a name without a view is a basic attribute. The view must be supported by the file system.

String

includeHiddenDirs (consumer (advanced))

Whether the consumer also reads hidden directories: directories whose name starts with a dot, or that the file system marks as hidden (such as with the hidden attribute on Windows). By default, they are skipped, also when the starting directory itself is hidden. The .camel directory, where the consumer moves the processed files by default, is always skipped.

false

boolean

includeHiddenFiles (consumer (advanced))

Whether the consumer also reads hidden files, which are files whose name starts with a dot. By default, they are skipped.

false

boolean

inProgressRepository (consumer (advanced))

A custom org.apache.camel.spi.IdempotentRepository that keeps track of the files being consumed, so that a later poll does not pick up a file that is still in progress. By default, a memory based repository (of up to 50000 entries) is used.

IdempotentRepository

localWorkDirectory (consumer (advanced))

A local directory to download the remote files into, so their content is stored in local files instead of in memory. Useful to save memory when consuming very big files. Not used by the file component.

String

onCompletionExceptionHandler (consumer (advanced))

A custom org.apache.camel.spi.ExceptionHandler that handles the exceptions thrown when the consumer completes a file, by a commit or a rollback (such as moving or deleting the file). By default, the exceptions are logged at WARN level and ignored.

ExceptionHandler

pollStrategy (consumer (advanced))

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

PollingConsumerPollStrategy

probeContentType (consumer (advanced))

Whether the consumer sets the CamelFileContentType header to the content type of the file, as java.nio.file.Files.probeContentType detects it. The result depends on the platform and is usually based on the file name extension; it is null when the type cannot be determined.

false

boolean

processStrategy (consumer (advanced))

A pluggable org.apache.camel.component.file.GenericFileProcessStrategy allowing you to implement your own readLock option or similar. Can also be used when special conditions must be met before a file can be consumed, such as a special ready file exists. If this option is set then the readLock option does not apply.

GenericFileProcessStrategy

startingDirectoryMustExist (consumer (advanced))

Whether the consumer fails to start when the starting directory does not exist. The autoCreate option, which is enabled by default, creates the missing directory, so this only has an effect when autoCreate is false.

false

boolean

startingDirectoryMustHaveAccess (consumer (advanced))

Whether the consumer fails to start when the JVM cannot read and write the starting directory. It requires startingDirectoryMustExist to be true: the consumer fails to start when only this option is set.

false

boolean

appendChars (producer)

Characters (text) to write after the content of each message, such as a new line or another separator between the messages. Only used with fileExist=Append. For a new line, carriage return or tab, use \n, \r or \t (a backslash and the letter).

String

checksumFileAlgorithm (producer)

The algorithm of a checksum to calculate from the content of the written file. The checksum is set in the CamelFileChecksum header (and written to a checksum file, see checksumWriteFile). The name is passed to java.security.MessageDigest, which accepts names such as MD5, SHA-1, SHA-256 or SHA3-256.

Enum values:

  • MD2

  • MD5

  • SHA_1

  • SHA_224

  • SHA_256

  • SHA_384

  • SHA_512

  • SHA_512_224

  • SHA_512_256

  • SHA3_224

  • SHA3_256

  • SHA3_384

  • SHA3_512

String

checksumWriteFile (producer)

Whether to also write the checksum to a file, when checksumFileAlgorithm is set. The checksum file is written in the same directory as the file, with the algorithm as extension (for example hello.txt.MD5 with checksumFileAlgorithm=MD5).

true

boolean

fileExist (producer)

What to do when a file with the same name already exists: - Override - replaces the existing file (the default). - Append - adds the content to the existing file. - Fail - fails with a GenericFileOperationFailedException. - Ignore - keeps the existing file and writes nothing, without failing. - Move - moves the existing file to the name given by the moveExisting option (which must be set) before writing the file. The eagerDeleteTargetFile option controls what happens when a file already exists at that name. - TryRename - only used with tempFileName or tempPrefix: renames the temporary file to the real name without checking whether a file exists, which can be faster on some file systems and FTP servers.

Enum values:

  • Override

  • Append

  • Fail

  • Ignore

  • Move

  • TryRename

Override

GenericFileExist

flatten (producer)

Whether to strip the leading paths from the file name, so only the name of the file is left. The consumer then sets the CamelFileName header to the name only, and the producer strips the paths from the name it writes (from the fileName option or the CamelFileName header). For example, files consumed recursively from subdirectories are then all written in a single directory.

false

boolean

moveExisting (producer)

Expression (such as File Language) used to compute file name to use when fileExist=Move is configured. To move files into a backup subdirectory just enter backup. This option only supports the following File Language tokens: file:name, file:name.ext, file:name.noext, file:onlyname, file:onlyname.noext, file:ext, and file:parent. Notice the file:parent is not supported by the FTP component, as the FTP component can only move any existing files to a relative directory based on current dir as base.

String

tempFileName (producer)

The same as tempPrefix option but offering a more fine grained control on the naming of the temporary filename as it uses the File Language. The location for tempFilename is relative to the final file location in the option 'fileName', not the target directory in the base uri. For example if option fileName includes a directory prefix: dir/finalFilename then tempFileName is relative to that subdirectory dir.

String

tempPrefix (producer)

This option is used to write the file using a temporary name and then, after the write is complete, rename it to the real name. Can be used to identify files being written and also avoid consumers (not using exclusive read locks) reading in progress files. Is often used by FTP when uploading big files.

String

allowNullBody (producer (advanced))

Whether a message with a null body can be written. If true, an empty file is written: an existing file is truncated with fileExist=Override, and left unchanged with fileExist=Append. If false, a null body fails with a GenericFileOperationFailedException.

false

boolean

chmod (producer (advanced))

The POSIX permissions to set on each file that the producer writes, as three octal digits such as 644. A fourth leading digit, as in 0644, is ignored. Requires a file system that supports POSIX permissions.

String

chmodDirectory (producer (advanced))

The POSIX permissions to set on each directory that the component creates (missing parent directories of a file the producer writes, and the starting directory created by autoCreate), as three octal digits such as 755. A fourth leading digit, as in 0755, is ignored. The directories are then created one level at a time. Requires a file system that supports POSIX permissions.

String

eagerDeleteTargetFile (producer (advanced))

Whether to delete an existing target file before the temporary file is written, when fileExist=Override is used with tempFileName or tempPrefix. Set it to false to keep the existing target file while the temporary file is written, for example when writing big files: the target file is then deleted just before the temporary file is renamed to it. With fileExist=Move, it also controls what happens when a file already exists at the name given by moveExisting: true deletes that file before the move, false fails the move with an exception.

true

boolean

forceWrites (producer (advanced))

Deprecated Has no effect: the producer does not force (sync) the written data to the storage device. Deprecated, to be removed in a future release.

false

boolean

keepLastModified (producer (advanced))

Whether to set the last modified timestamp of the written file to the value of the CamelFileLastModified header (a java.util.Date or a long), for example to keep the timestamp of the source file. Nothing is set when the header is missing. Only used by the file component.

false

boolean

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

moveExistingFileStrategy (producer (advanced))

A custom FileMoveExistingStrategy that moves the existing file when fileExist=Move is used. By default, the component uses its own implementation, which moves the file to the name computed by moveExisting.

FileMoveExistingStrategy

autoCreate (advanced)

Automatically create missing directories in the file’s pathname. For the file consumer, that means creating the starting directory. For the file producer, it means the directory the files should be written to.

true

boolean

autoCreateStepwise (advanced)

Whether to create missing directories one level at a time (File.mkdir for each level) instead of all levels in one call (File.mkdirs). Some file shares need this. When the chmodDirectory option is set, the directories are always created one level at a time.

false

boolean

browseLimit (advanced)

Maximum number of messages to keep in memory available for browsing. Use 0 for unlimited.

100

int

bufferSize (advanced)

Buffer size in bytes used for writing files (or in case of FTP for downloading and uploading files).

131072

int

charsetErrorAction (advanced)

What to do with malformed input and unmappable characters when a file is read or written with a charset. REPORT fails with a MalformedInputException or an UnmappableCharacterException. REPLACE replaces the character with the replacement of the charset (U+FFFD when reading, '?' when writing ISO-8859-1 for example). IGNORE drops the character. The consumer uses it when the file content is read as text (such as a String or a Reader), and as an InputStream or byte[] when the charset option is set. The producer uses it only when the charset option is set. REPLACE and IGNORE change the data, so only use them when losing these characters is acceptable.

Enum values:

  • REPORT

  • REPLACE

  • IGNORE

REPORT

CharsetErrorAction

copyAndDeleteOnRenameFail (advanced)

Whether to copy the file to the target and then delete the original when the file cannot be renamed (moved), for example when the target is on another file system. The copy is used after 3 failed rename attempts, which take about 2 seconds. Files are renamed, for example, by the move, preMove and moveFailed options of the consumer, and by the tempFileName and moveExisting options of the producer.

true

boolean

renameUsingCopy (advanced)

Whether to rename (move) files by copying them to the target and then deleting the original, instead of renaming them. Use it where the regular rename is unreliable, for example across file systems or on network shares. It takes precedence over copyAndDeleteOnRenameFail, which copies the file only after the rename attempts have failed.

false

boolean

synchronous (advanced)

Whether the consumer routes each file synchronously, so the poll waits until the route has finished with the file. By default, the consumer uses the asynchronous routing engine: when the route continues on another thread, the poll goes on with the next file.

false

boolean

antExclude (filter)

Excludes the files whose path, relative to the starting directory, matches one of these Ant style patterns, such as */.bak. Separate several patterns with a comma. Takes precedence over antInclude.

String

antFilterCaseSensitive (filter)

Whether the antInclude and antExclude patterns are matched case sensitive.

true

boolean

antInclude (filter)

Includes only the files whose path, relative to the starting directory, matches one of these Ant style patterns, such as */.txt. Separate several patterns with a comma.

String

eagerMaxMessagesPerPoll (filter)

Allows for controlling whether the limit from maxMessagesPerPoll is eager or not. If eager then the limit is during the scanning of files, and the file, sftp, mina-sftp and smb consumers stop reading the directory once the limit is hit, unless preSort or doneFileName is used, as they need the whole directory. Where as false would scan all files, and then perform sorting. Setting this option to false allows for sorting all files first, and then limit the poll. Mind that this requires a higher memory usage as all file details are in memory to perform the sorting.

true

boolean

exclude (filter)

Excludes the files whose name matches this regular expression (matched ignoring the case). Takes precedence over include. It is a regular expression, not a wildcard: use antExclude for wildcards, or excludeExt to exclude files by extension. When the expression has characters such as the plus sign, set it with RAW() in an endpoint URI.

String

excludeExt (filter)

Excludes the files with one of these extensions (ignoring the case), separated by comma, for example excludeExt=bak,dat. A file matches when its name ends with a dot and the extension, so both excludeExt=gz and excludeExt=tar.gz match mydata.tar.gz. For more flexibility use the include and exclude options.

String

filter (filter)

Pluggable filter as a org.apache.camel.component.file.GenericFileFilter class. Will skip files if filter returns false in its accept() method.

GenericFileFilter

filterDirectory (filter)

A File Language predicate that filters the subdirectories to scan with recursive=true: only the directories for which it is true are scanned. For example, to scan only the directory of today: $\{file:onlyname} == $\{date:now:yyyyMMdd}.

String

filterFile (filter)

A File Language predicate that filters the files: only the files for which it is true are consumed. For example, to filter on the file extension: $\{file:ext} == 'txt'.

String

idempotent (filter)

Option to use the Idempotent Consumer EIP pattern to let Camel skip already processed files. Will by default use a memory based LRUCache that holds 1000 entries. If noop=true then idempotent will be enabled as well to avoid consuming the same files over and over again. Setting only idempotentRepository or idempotentKey does not turn it on.

false

Boolean

idempotentEager (filter)

Sets whether to eagerly add the filename to the idempotent repository or wait until the exchange is complete. Does not apply with an idempotent read lock (readLock=idempotent, idempotent-changed or idempotent-rename), which adds the filename when it acquires the lock.

true

Boolean

idempotentKey (filter)

To use a custom idempotent key. By default the absolute path of the file is used. You can use the File Language, for example to use the file name and file size, you can do: idempotentKey=$\{file:name}-$\{file:size}. It is used only with idempotent=true (noop=true turns it on), or by an idempotent read lock (readLock=idempotent, idempotent-changed or idempotent-rename) of the file component.

String

idempotentRepository (filter)

A pluggable repository org.apache.camel.spi.IdempotentRepository which by default use MemoryIdempotentRepository if none is specified and idempotent is true. It is used only with idempotent=true (noop=true turns it on), or by an idempotent read lock (readLock=idempotent, idempotent-changed or idempotent-rename) of the file component. Set without them, it does not skip any file.

IdempotentRepository

include (filter)

Includes only the files whose name matches this regular expression (matched ignoring the case). It is a regular expression, not a wildcard: use antInclude for wildcards, or includeExt to include files by extension. When the expression has characters such as the plus sign, set it with RAW() in an endpoint URI.

String

includeExt (filter)

Includes only the files with one of these extensions (ignoring the case), separated by comma, for example includeExt=txt,xml. A file matches when its name ends with a dot and the extension, so both includeExt=gz and includeExt=tar.gz match mydata.tar.gz. For more flexibility use the include and exclude options.

String

maxDepth (filter)

The maximum depth to traverse when recursively processing a directory. maxDepth=1 means only the starting directory.

2147483647

int

maxMessagesPerPoll (filter)

The maximum number of files to consume in one poll. 0 or negative (the default) means no limit. Can be used, for example, to avoid picking up thousands of files at once when the server starts. With eagerMaxMessagesPerPoll=true (the default) the limit applies while the files are scanned, before any sorting: with 100000 files and maxMessagesPerPoll=500, the first 500 files found are taken and then sorted. Set eagerMaxMessagesPerPoll=false to scan and sort all the files first, and then take the limit.

int

minDepth (filter)

The minimum depth to start processing when recursively processing a directory. Using minDepth=1 means the base directory. Using minDepth=2 means the first sub directory.

int

move (filter)

Expression (such as Simple Language) used to dynamically set the filename when moving it after processing. To move files into a .done subdirectory just enter .done.

String

exclusiveReadLockStrategy (lock)

A custom org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy to use as the read lock. When set, the readLock option is not used.

GenericFileExclusiveReadLockStrategy

readLock (lock)

Used by the consumer to only pick up a file that is not in progress (being written), by first getting an exclusive read lock on it. The consumer waits until the lock is granted (see readLockTimeout). The supported read locks are: - none - No read lock is used. - markerFile - Camel creates a marker file (the file name with the .camelLock extension), and does not pick up a file that already has one. - changed - Uses the file length and modification timestamp to detect whether the file is still being written. It takes at least readLockCheckInterval to decide, so it cannot consume files as fast as the others, but it can be more reliable, as the JDK IO API cannot always detect whether another process is using a file. - fileLock - Uses java.nio.channels.FileLock. Not supported on Windows. Avoid it on a remote file system mounted as a share, unless that file system supports distributed file locks. - rename - Tries to rename the file, to test whether it can get an exclusive read lock. - idempotent - Uses the idempotentRepository as the read lock. This supports clustering if the idempotent repository implementation does. - idempotent-changed - Combines the idempotentRepository and changed as the read lock. This supports clustering if the idempotent repository implementation does. - idempotent-rename - Combines the idempotentRepository and rename as the read lock. This supports clustering if the idempotent repository implementation does. Not all read locks suit a cluster, where consumers on several nodes compete for the same files on a shared file system. markerFile creates the marker file with a close to atomic operation, but this is not guaranteed to work in a cluster. fileLock may work better, but the file system must support distributed file locks. The idempotent read locks support clustering if the idempotent repository does, such as the ones of the Hazelcast or Infinispan components.

Enum values:

  • none

  • markerFile

  • fileLock

  • rename

  • changed

  • idempotent

  • idempotent-changed

  • idempotent-rename

none

String

readLockCheckInterval (lock)

The interval in millis between the attempts to acquire the read lock, for the read locks that retry (changed, fileLock and rename, and also idempotent-changed and idempotent-rename of the file component). For example, set a higher interval with readLock=changed to cater for slow writes. The ftp, ftps, sftp, mina-sftp and azure-files components use 5000 by default. readLockTimeout must be higher than readLockCheckInterval; as a rule of thumb, make the timeout at least 2 or 3 times the interval, so the read lock has enough time to be acquired before the timeout.

1000

long

readLockDeleteOrphanLockFiles (lock)

Whether to delete, when the consumer starts, the marker files (.camelLock) left in the directory, for example after the JVM crashed. Used by the markerFile, changed and fileLock read locks. If false, a file with an orphaned marker file is not picked up; such a marker file may also belong to another node that reads the same shared directory.

true

boolean

readLockIdempotentReleaseAsync (lock)

Whether the delayed release of readLockIdempotentReleaseDelay runs asynchronously on a scheduled thread pool, instead of blocking the thread for the delay.

false

boolean

readLockIdempotentReleaseAsyncPoolSize (lock)

The number of core threads of the scheduled thread pool that runs the delayed release tasks with readLockIdempotentReleaseAsync=true. Not used when readLockIdempotentReleaseExecutorService is set. Only raise it when updating the idempotent repository is slow, or there are a lot of files to process.

int

readLockIdempotentReleaseDelay (lock)

The delay in millis before the read lock of readLock=idempotent or idempotent-changed is released, that is, before the key of the file is removed from or confirmed in the idempotent repository on commit or rollback. In an active/active cluster with a shared idempotent repository, the delay widens the time in which the file counts as locked, so other nodes do not pick up the same file due to a race condition; this matters when the key is removed, as with readLockRemoveOnCommit=true. The delay blocks the thread, unless readLockIdempotentReleaseAsync is true or readLockIdempotentReleaseExecutorService is set. 0 (the default) means no delay.

int

readLockIdempotentReleaseExecutorService (lock)

A custom (for example shared) scheduled thread pool that runs the delayed release tasks of readLockIdempotentReleaseDelay; setting it makes the release asynchronous.

ScheduledExecutorService

readLockLoggingLevel (lock)

The logging level of the message logged when a read lock cannot be acquired, for example OFF for no logging. Used by the read locks changed, fileLock, idempotent, idempotent-changed, idempotent-rename and rename.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

DEBUG

LoggingLevel

readLockMarkerFile (lock)

Whether the changed, fileLock and rename read locks also create a marker file, to keep other processes from picking up the same files. Set it to false, for example, to not write marker files to the file system. Only used by the file component.

true

boolean

readLockMinAge (lock)

The minimum age in millis a file must have before the changed read lock (readLock=changed or idempotent-changed) acquires it, for example readLockMinAge=300s for 5 minutes. When set, the read lock acquires a file as soon as it is older than this, without waiting for its length and timestamp to stay the same, which can make it faster.

0

long

readLockMinLength (lock)

The minimum length in bytes a file must have before the changed read lock (readLock=changed or idempotent-changed) acquires it. The default 1 means an empty file is not consumed; set 0 to consume empty files.

1

long

readLockRemoveOnCommit (lock)

Used by the idempotent read locks (readLock=idempotent, idempotent-changed or idempotent-rename): whether to remove the key of the file from the idempotent repository when the file was processed successfully (commit). By default the key is kept (confirmed), so another active node does not pick up the file due to a race condition; the idempotent repository can evict the key later, if it supports eviction. See also readLockIdempotentReleaseDelay.

false

boolean

readLockRemoveOnRollback (lock)

Used by the idempotent read locks (readLock=idempotent, idempotent-changed or idempotent-rename): whether to remove the key of the file from the idempotent repository when processing the file failed (rollback), so the file can be picked up again. If false, the key is confirmed instead, as on a commit.

true

boolean

readLockTimeout (lock)

The timeout in millis to acquire the read lock. When the lock is not granted within the timeout, the file is skipped and tried again on the next poll. 0 or lower waits forever. Used by the changed, fileLock and rename read locks (and also idempotent-changed and idempotent-rename of the file component). The ftp, ftps, sftp, mina-sftp and azure-files components use 20000 by default. readLockTimeout must be higher than readLockCheckInterval; as a rule of thumb, make the timeout at least 2 or 3 times the interval, so the read lock has enough time to be acquired before the timeout.

10000

long

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

int

delay (scheduler)

Milliseconds before the next poll.

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

healthCheckMaxPollDuration (scheduler)

How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off.

0

long

initialDelay (scheduler)

Milliseconds before the first poll starts.

1000

long

repeatCount (scheduler)

Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever.

0

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

ScheduledExecutorService

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler.

none

Object

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. This is a multi-value option with prefix: scheduler.

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

Enum values:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

shuffle (sort)

To shuffle the list of files (sort in random order).

false

boolean

sortBy (sort)

Sorts the files with File Language expressions, such as sortBy=file:name. Separate several groups with a semicolon to sort by the next group when the previous one is equal, such as sortBy=file:modified;file:name. Prefix a group with reverse: to sort it in reverse order, and with ignoreCase: to compare text ignoring the case (reverse: comes first when both are used).

String

sorter (sort)

Pluggable sorter as a java.util.Comparator class that compares org.apache.camel.component.file.GenericFile objects.

Comparator

Message Headers

The File component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelFileLength (consumer)

Constant: FILE_LENGTH

The size of the file in bytes.

long

CamelFileLastModified (consumer)

Constant: FILE_LAST_MODIFIED

The last modified time of the file, in milliseconds since the epoch (1970-01-01T00:00:00Z). With the keepLastModified option, the producer sets this time (a Long or a java.util.Date) on the file it writes.

long

CamelMessageTimestamp (consumer)

Constant: MESSAGE_TIMESTAMP

The last modified time of the consumed file, in milliseconds since the epoch: the same value as CamelFileLastModified. Only set when the last modified time is known.

long

CamelFileLocalWorkPath (producer)

Constant: FILE_LOCAL_WORK_PATH

The path of the local work file, which a remote file consumer (such as FTP) sets when it uses the localWorkDirectory option. When the message body is a file, the file producer moves this local work file to the target instead of copying the body.

String

CamelFileNameOnly (consumer)

Constant: FILE_NAME_ONLY

Only the file name (the name with no leading paths).

String

CamelFileName (common)

Constant: FILE_NAME

Consumer: the name of the consumed file, relative to the starting directory (with the flatten option, only the file name). Producer: the name of the file to write, relative to the starting directory; it can be a String, which is used as is (not evaluated as an expression), or an Expression, which is evaluated. The fileName option takes precedence over this header, unless the header is an Expression. When neither is set, the producer uses the message ID as the file name.

String

CamelFileNameConsumed (consumer)

Constant: FILE_NAME_CONSUMED

The name of the consumed file, relative to the starting directory. Unlike CamelFileName, it keeps this value when the route or the flatten option changes CamelFileName.

String

CamelFileAbsolute (consumer)

Constant: FILE_ABSOLUTE

Whether the path of the consumed file is absolute, which is the case when the starting directory is an absolute path.

Boolean

CamelFileAbsolutePath (consumer)

Constant: FILE_ABSOLUTE_PATH

The absolute path of the consumed file, including its name.

String

CamelFileExtendedAttributes (consumer)

Constant: FILE_EXTENDED_ATTRIBUTES

The file attributes read with the extendedAttributes option, as a Map keyed by view:name, such as posix:owner.

Map

CamelFileContentType (consumer)

Constant: FILE_CONTENT_TYPE

The content type of the consumed file, as java.nio.file.Files.probeContentType detects it. Only set when the probeContentType option is enabled.

String

CamelFilePath (consumer)

Constant: FILE_PATH

The path of the consumed file, including its name: the absolute path when the starting directory is absolute, otherwise the starting directory followed by the relative path of the file.

String

CamelFileRelativePath (consumer)

Constant: FILE_RELATIVE_PATH

The path of the consumed file relative to the starting directory, including its name.

String

CamelFileParent (common)

Constant: FILE_PARENT

The path of the directory that holds the file. The consumer sets it for the consumed file, and the producer for the existing file when it evaluates the moveExisting option.

String

CamelFileNameProduced (producer)

Constant: FILE_NAME_PRODUCED

The path (directory and name) of the file that the producer wrote. It is absolute when the starting directory is an absolute path.

String

CamelOverruleFileName (producer)

Constant: OVERRULE_FILE_NAME

The name of the file to write, used instead of CamelFileName for one write: the producer uses it as CamelFileName, then removes it after writing the file and restores the previous CamelFileName. It can be a String (or a value that converts to a String) or an Expression. When the fileName option is set, it still takes precedence, unless this header is an Expression.

Object

CamelFileInitialOffset (consumer)

Constant: INITIAL_OFFSET

The consumed file and the offset to resume reading it from, as an org.apache.camel.resume.Resumable. The offset is the one that the resume strategy of the consumer has for the file, and is null when there is none.

Resumable

CamelFileChecksum (producer)

Constant: FILE_CHECKSUM

The checksum of the file that the producer wrote, as a hexadecimal string, computed with the algorithm of the checksumFileAlgorithm option. Only set when that option is set.

String

Message Body

The message body at each side of the File component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

file

The file as read: a GenericFile (a java.io.File with preMove), which converts to text, bytes or a stream.

Producer input

text, bytes, stream or file

What converts to an InputStream: text, bytes, a stream or a file. A Map or a List fails: marshal it first.

  • With allowNullBody=true: null, text, bytes, stream or file

Producer output

unchanged

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Default behavior for file producer

By default, it will override any existing file if one exists with the same name.

Usage

Move, Pre Move and Delete operations

By default, Camel will move consumed files to the .camel subfolder relative to the directory where the file was consumed.

If you want to delete the file after processing, the route should be:

  • Java

  • XML

  • YAML

from("file://inbox?delete=true").to("bean:handleOrder");
<route>
  <from uri="file://inbox?delete=true"/>
  <to uri="bean:handleOrder"/>
</route>
- route:
    from:
      uri: file://inbox
      parameters:
        delete: true
      steps:
        - to:
            uri: bean:handleOrder
noop=true leaves the files in place, so it does not go with delete=true or move. With delete=true the files are deleted (delete wins), and with move they are not moved (noop wins); the consumer logs a WARN for both. delete=true with move fails when the consumer is created.

Move, Delete and the Routing process

Any move or delete operations are executed after the routing has completed. So, during processing of the Exchange the file is still located in the inbox folder.

Let’s illustrate this with an example:

  • Java

  • XML

  • YAML

from("file://inbox?move=.done").to("bean:handleOrder");
<route>
  <from uri="file://inbox?move=.done"/>
  <to uri="bean:handleOrder"/>
</route>
- route:
    from:
      uri: file://inbox
      parameters:
        move: .done
      steps:
        - to:
            uri: bean:handleOrder

When a file is dropped in the inbox folder, the file consumer notices this and creates a new FileExchange that is routed to the handleOrder bean. The bean then processes the File object. At this point in time the file is still located in the inbox folder. After the bean completes, and thus the route is completed, the file consumer will perform the move operation and move the file to the .done sub-folder.

The move and the preMove options are considered as a directory name. Though, if you use an expression such as File Language, or Simple, then the result of the expression evaluation is the file name to be used. E.g., if you set:

move=../backup/copy-of-${file:name}

Then that’s using the File Language which we use to return the file name to be used. This can be either relative or absolute. If relative, the directory is created as a subfolder from within the folder where the file was consumed.

Move and Pre Move operations

We have introduced a preMove operation to move files before they are processed. This allows you to mark which files have been scanned as they are moved to this subfolder before being processed.

  • Java

  • XML

  • YAML

from("file://inbox?preMove=inprogress").to("bean:handleOrder");
<route>
  <from uri="file://inbox?preMove=inprogress"/>
  <to uri="bean:handleOrder"/>
</route>
- route:
    from:
      uri: file://inbox
      parameters:
        preMove: inprogress
      steps:
        - to:
            uri: bean:handleOrder

You can combine the preMove and the regular move:

  • Java

  • XML

  • YAML

from("file://inbox?preMove=inprogress&move=.done").to("bean:handleOrder");
<route>
  <from uri="file://inbox?preMove=inprogress&amp;move=.done"/>
  <to uri="bean:handleOrder"/>
</route>
- route:
    from:
      uri: file://inbox
      parameters:
        preMove: inprogress
        move: .done
      steps:
        - to:
            uri: bean:handleOrder

So in this situation, the file is in the inprogress folder when being processed, and after it’s processed, it’s moved to the .done folder.

Fine-grained control over Move and PreMove option

The move and preMove options are Expression-based, so we have the full power of the File Language to do advanced configuration of the directory and name pattern. Camel will, in fact, internally convert the directory name you enter into a File Language expression. So, when we use move=.done Camel will convert this into: ${file:parent}/.done/${file:onlyname}.

This is only done if Camel detects that you have not provided a ${ } in the option value yourself. So when you enter a ${ } Camel will not convert it, and thus you have the full power.

So if we want to move the file into a backup folder with today’s date, as the pattern, we can do:

move=backup/${date:now:yyyyMMdd}/${file:name}

About moveFailed

The moveFailed option allows you to move files that could not be processed successfully to another location such as an error folder of your choice. For example, to move the files in an error folder with a timestamp you can use moveFailed=/error/${file:name.noext}-${date:now:yyyyMMddHHmmssSSS}.${``file:ext}.

See more examples at File Language

Exchange Properties, file consumer only

As the file consumer implements the BatchConsumer it supports batching the files it polls. By batching, we mean that Camel will add the following additional properties to the Exchange:

Property Description

CamelBatchSize

The total number of files that was polled in this batch.

CamelBatchIndex

The current index of the batch. Starts from 0.

CamelBatchComplete

A boolean value indicating the last Exchange in the batch. Is only true for the last entry.

This allows you, for instance, to know how many files exist in this batch and for instance, let the Aggregator2 aggregate this number of files.

Using charset

The charset option allows configuring the encoding of the files on both the consumer and producer endpoints. For example, if you read utf-8 files and want to convert the files to iso-8859-1, you can do:

  • Java

  • XML

  • YAML

from("file:inbox?charset=utf-8")
  .to("file:outbox?charset=iso-8859-1")
<route>
  <from uri="file:inbox?charset=utf-8"/>
  <to uri="file:outbox?charset=iso-8859-1"/>
</route>
- route:
    from:
      uri: file:inbox
      parameters:
        charset: utf-8
      steps:
        - to:
            uri: file:outbox
            parameters:
              charset: iso-8859-1

You can also use the convertBodyTo in the route. In the example below, we have still input files in utf-8 format, but we want to convert the file content to a byte array in iso-8859-1 format. And then let a bean process the data. Before writing the content to the outbox folder using the current charset.

  • Java

  • XML

  • YAML

from("file:inbox?charset=utf-8")
  .convertBodyTo(byte[].class, "iso-8859-1")
  .to("bean:myBean")
  .to("file:outbox");
<route>
  <from uri="file:inbox?charset=utf-8"/>
  <convertBodyTo type="byte[]" charset="iso-8859-1"/>
  <to uri="bean:myBean"/>
  <to uri="file:outbox"/>
</route>
- route:
    from:
      uri: file:inbox
      parameters:
        charset: utf-8
      steps:
        - convertBodyTo:
            type: "byte[]"
            charset: iso-8859-1
        - to:
            uri: bean:myBean
        - to:
            uri: file:outbox

If you omit the charset on the consumer endpoint, then Camel does not know the charset of the file, and would by default use UTF-8. However, you can configure a JVM system property to override and use a different default encoding with the key org.apache.camel.default.charset.

In the example below, this could be a problem if the files are not in UTF-8 encoding, which would be the default encoding for read the files. In this example when writing the files, the content has already been converted to a byte array, and thus would write the content directly as is (without any further encodings).

  • Java

  • XML

  • YAML

from("file:inbox")
  .convertBodyTo(byte[].class, "iso-8859-1")
  .to("bean:myBean")
  .to("file:outbox");
<route>
  <from uri="file:inbox"/>
  <convertBodyTo type="byte[]" charset="iso-8859-1"/>
  <to uri="bean:myBean"/>
  <to uri="file:outbox"/>
</route>
- route:
    from:
      uri: file:inbox
      steps:
        - convertBodyTo:
            type: "byte[]"
            charset: iso-8859-1
        - to:
            uri: bean:myBean
        - to:
            uri: file:outbox

You can also override and control the encoding dynamic when writing files, by setting a property on the exchange with the key Exchange.CHARSET_NAME. For example, in the route below, we set the property with a value from a message header.

  • Java

  • XML

  • YAML

from("file:inbox")
  .convertBodyTo(byte[].class, "iso-8859-1")
  .to("bean:myBean")
  .setProperty(Exchange.CHARSET_NAME, header("someCharsetHeader"))
  .to("file:outbox");
<route>
  <from uri="file:inbox"/>
  <convertBodyTo type="byte[]" charset="iso-8859-1"/>
  <to uri="bean:myBean"/>
  <setProperty name="CamelCharsetName">
    <header>someCharsetHeader</header>
  </setProperty>
  <to uri="file:outbox"/>
</route>
- route:
    from:
      uri: file:inbox
      steps:
        - convertBodyTo:
            type: "byte[]"
            charset: iso-8859-1
        - to:
            uri: bean:myBean
        - setProperty:
            name: CamelCharsetName
            header: someCharsetHeader
        - to:
            uri: file:outbox

We suggest keeping things simpler, so if you pick up files with the same encoding, and want to write the files in a specific encoding, then favor to use the charset option on the endpoints.

Notice that if you have explicitly configured a charset option on the endpoint, then that configuration is used, regardless of the Exchange.CHARSET_NAME property.

If you have some issues then you can enable DEBUG logging on org.apache.camel.component.file, and Camel logs when it reads/write a file using a specific charset. For example, the route below will log the following:

  • Java

  • XML

  • YAML

from("file:inbox?charset=utf-8")
  .to("file:outbox?charset=iso-8859-1")
<route>
  <from uri="file:inbox?charset=utf-8"/>
  <to uri="file:outbox?charset=iso-8859-1"/>
</route>
- route:
    from:
      uri: file:inbox
      parameters:
        charset: utf-8
      steps:
        - to:
            uri: file:outbox
            parameters:
              charset: iso-8859-1

And the logs:

DEBUG GenericFileConverter           - Read file /Users/davsclaus/workspace/camel/camel-core/target/charset/input/input.txt with charset utf-8
DEBUG FileOperations                 - Using Reader to write file: target/charset/output.txt with charset: iso-8859-1

Characters the charset cannot read or write

By default, Camel fails when the content of a file does not fit the charset:

  • Reading a file whose bytes are not valid in the charset fails with a MalformedInputException, for example a file in ISO-8859-1 that is read as UTF-8.

  • Reading a byte the charset does not map to a character fails with an UnmappableCharacterException, for example the byte 0x81 in windows-1252.

  • Writing a character the charset cannot encode fails with an UnmappableCharacterException, for example the euro sign (€) written as ISO-8859-1.

The charsetErrorAction option decides what happens instead:

Value Description

REPORT

Fail with the exception. This is the default.

REPLACE

Replace the character with the replacement of the charset: U+FFFD when reading, and ? when writing ISO-8859-1, for example.

IGNORE

Drop the character.

When the option applies:

  • On the consumer, when the file content is read as text, such as a String or a Reader (convertBodyTo, a bean that takes a String, and so on). This also applies without the charset option: the file is then read with the charset of the exchange or the default charset. When the content is read as an InputStream or a byte[], the option applies only when the charset option is set: without it, Camel reads the bytes of the file as they are, and decodes nothing.

  • Not on a consumer with the preMove option: the message body is then the moved file as a java.io.File, which Camel reads with the charset, but without this option.

  • On the producer, only when the charset option is set: Camel then encodes the message body with that charset when writing the file.

REPLACE and IGNORE change the data. With IGNORE the content is also shorter than the file, which matters for formats with fixed-width records. Use them only when losing these characters is acceptable.

The option is only on the file component. The FTP, SFTP and SMB components replace these characters already.

For example, to read files in UTF-8 and write them in ISO-8859-1, with a replacement character where a character cannot be read or written:

  • Java

  • XML

  • YAML

from("file:inbox?charset=utf-8&charsetErrorAction=REPLACE")
  .to("file:outbox?charset=iso-8859-1&charsetErrorAction=REPLACE");
<route>
  <from uri="file:inbox?charset=utf-8&amp;charsetErrorAction=REPLACE"/>
  <to uri="file:outbox?charset=iso-8859-1&amp;charsetErrorAction=REPLACE"/>
</route>
- route:
    from:
      uri: file:inbox
      parameters:
        charset: utf-8
        charsetErrorAction: REPLACE
      steps:
        - to:
            uri: file:outbox
            parameters:
              charset: iso-8859-1
              charsetErrorAction: REPLACE

Common gotchas with folder and filenames

When Camel is producing files (writing files), there are a few gotchas affecting how to set a filename of your choice. By default, Camel will use the message ID as the filename, and since the message ID is normally a unique generated ID, you will end up with filenames such as: ID-MACHINENAME-2443-1211718892437-1-0. If such a filename is not desired, then you must provide a filename in the CamelFileName message header. The constant, Exchange.FILE_NAME, can also be used.

The sample code below produces files using the message ID as the filename:

  • Java

  • XML

  • YAML

from("direct:report").to("file:target/reports");
<route>
  <from uri="direct:report"/>
  <to uri="file:target/reports"/>
</route>
- route:
    from:
      uri: direct:report
      steps:
        - to:
            uri: file:target/reports

To use report.txt as the filename you have to do (using the CamelFileName header):

  • Java

  • XML

  • YAML

from("direct:report").setHeader("CamelFileName", constant("report.txt")).to("file:target/reports");
<route>
  <from uri="direct:report"/>
  <setHeader name="CamelFileName">
    <constant>report.txt</constant>
  </setHeader>
  <to uri="file:target/reports"/>
</route>
- route:
    from:
      uri: direct:report
      steps:
        - setHeader:
            name: CamelFileName
            constant: report.txt
        - to:
            uri: file:target/reports

And a syntax where we set the filename on the endpoint with the fileName URI option.

  • Java

  • XML

  • YAML

from("direct:report").to("file:target/reports/?fileName=report.txt");
<route>
  <from uri="direct:report"/>
  <to uri="file:target/reports/?fileName=report.txt"/>
</route>
- route:
    from:
      uri: direct:report
      steps:
        - to:
            uri: file:target/reports/
            parameters:
              fileName: report.txt

Filename Expression

The filename can be set with the fileName option, as a File Language expression, or with the CamelFileName header. A String in the header is used as is, not evaluated as an expression; to compute the name in the header, set an Expression object, or set the header with an expression in the route (such as setHeader with simple). See the File Language for syntax and samples.

Consuming files from folders where others drop files directly

Beware if you consume files from a folder where other applications write files too. Take a look at the different readLock options to see what suits your use cases. The best approach is, however, to write to another folder and, after writing, move the file in the drop folder. However, if you write files directly to the drop folder, then the option changed could better detect whether a file is currently being written/copied as it uses a file changed algorithm to see whether the file size / modification changes over a period of time. The other readLock options rely on Java File API that, sadly, is not always very good at detecting this. You may also want to look at the doneFileName option, which uses a marker file (done file) to signal when a file is done and ready to be consumed.

With jailStartingDirectory enabled (the default), symbolic links are resolved when checking that a file stays within the starting directory. The consumer skips a file, or with recursive=true a directory, that is a link resolving outside the starting directory (logged at WARN the first time), and the producer fails to write through such a link.

The consumer also checks where it would move a file: the targets of preMove, move and moveFailed, including the default .camel folder. It checks them before the file is processed (and before the read lock is acquired), so the expressions of these options are evaluated one extra time per file: for a file processed without error, move is evaluated twice and moveFailed once. Keep this in mind for an expression with side effects, such as a bean that hands out a sequence number. When a target is inside the starting directory but resolves outside of it through a link, the consumer skips the file (logged at WARN the first time). The file is not processed and stays in the folder. This applies to moveFailed too, even when the file would be processed without errors. A target that depends on what the route sets, such as an exchange property, can only be checked when the file is moved. When such a target resolves outside, the move fails like any other failed move, and the file is consumed again on the next poll.

The producer checks the files it deletes or renames onto in the same way: with fileExist=Move and moveExisting, and when it renames a file written with tempFileName. Such a write fails.

A target configured outside the starting directory (such as move=../archive) is not checked. Links that resolve inside the starting directory, and a starting directory that is itself a link, work as usual. When a folder such as .camel is linked to another volume on purpose, point the option at the folder the link resolves to, such as move=/mnt/volume2/${file:name}. Setting jailStartingDirectory=false also keeps following such links, but then the consumer also reads a file in the starting directory that is a link to a file outside of it, and the producer writes through such links. The check and the read or write that follows are not atomic, so the permissions of the directories still matter.

Done files

Using done files

See also section writing done files below.

If you want only to consume files when a done file exists, then you can use the doneFileName option on the endpoint.

  • Java

  • XML

  • YAML

from("file:bar?doneFileName=done");
<from uri="file:bar?doneFileName=done"/>
- from:
    uri: file:bar
    parameters:
      doneFileName: done
    steps:
      - log:
          message: "${header.CamelFileName}"

It will only consume files from the bar folder if a done file exists in the same directory as the target files. Camel will automatically delete the done file when it’s done consuming the files. When a poll leaves files of the directory for the next poll (beyond maxMessagesPerPoll, or not started, for example when the read lock is not acquired), the done file is kept until they are consumed; meanwhile the polls consume every file of the directory, as they do whenever the done file is there. With recursive=true each directory has its own done file, which the last file of that directory in the poll deletes.

Camel does not delete automatically the done file if noop=true is configured.

However, it is more common to have one done file per target file. This means there is a 1:1 correlation. To do this, you must use dynamic placeholders in the doneFileName option. Currently, Camel supports the following two dynamic tokens: file:name and file:name.noext which must be enclosed in ${ }. The consumer only supports the static part of the done file name as either prefix or suffix (not both).

  • Suffix

  • Prefix

from("file:bar?doneFileName=${file:name}.done");

In this example, the files will only be polled if there exists a done file with the name file name.done. For example:

  • hello.txt: is the file to be consumed

  • hello.txt.done: is the associated done file

from("file:bar?doneFileName=ready-${file:name}");

You can also use a prefix for the done file, such as:

  • hello.txt: is the file to be consumed

  • ready-hello.txt: is the associated done file

Writing done files

After you have written a file, you may want to write an additional done file as a kind of marker, to indicate to others that the file is finished and has been written. To do that, you can use the doneFileName option on the file producer endpoint.

  • Java

  • XML

  • YAML

.to("file:bar?doneFileName=done");
<to uri="file:bar?doneFileName=done"/>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: file:bar
            parameters:
              doneFileName: done

This will create a file named done in the same directory as the target file.

However, it is more common to have one done file per target file. This means there is a 1:1 correlation. To do this, you must use dynamic placeholders in the doneFileName option. Currently, Camel supports the following two dynamic tokens: file:name and file:name.noext. They must be enclosed in ${ }:

  • Prefix and file name

  • Suffix and file name

  • File name without the extension

.to("file:bar?doneFileName=done-${file:name}");

This will, for example, create a file named done-foo.txt if the target file was foo.txt in the same directory as the target file.

.to("file:bar?doneFileName=${file:name}.done");

This will, for example, create a file named foo.txt.done if the target file was foo.txt in the same directory as the target file.

.to("file:bar?doneFileName=${file:name.noext}.done");

Will, for example, create a file named foo.done if the target file was foo.txt in the same directory as the target file.

Using flatten

If you want to store the files in the outputdir directory in the same directory, disregarding the source directory layout (e.g., to flatten out the path), you add the flatten=true option on the file producer side:

  • Java

  • XML

  • YAML

from("file://inputdir/?recursive=true&delete=true").to("file://outputdir?flatten=true")
<route>
  <from uri="file://inputdir/?recursive=true&amp;delete=true"/>
  <to uri="file://outputdir?flatten=true"/>
</route>
- route:
    from:
      uri: file://inputdir/
      parameters:
        recursive: true
        delete: true
      steps:
        - to:
            uri: file://outputdir
            parameters:
              flatten: true

It will result in the following output layout:

outputdir/foo.txt
outputdir/bar.txt

Writing to files

Camel is also able to write files, i.e., produce files. In the sample below, we receive some reports on the SEDA queue that we process before they are being written to a directory.

Write to subdirectory using Exchange.FILE_NAME

Using a single route, it is possible to write a file to any number of subdirectories. If you have a route setup as such:

  • Java

  • XML

  • YAML

from("seda:reports")
    .to("bean:myBean")
    .to("file:/rootDirectory");
<route>
  <from uri="seda:reports"/>
  <to uri="bean:myBean"/>
  <to uri="file:/rootDirectory"/>
</route>
- route:
    from:
      uri: seda:reports
      steps:
        - to:
            uri: bean:myBean
        - to:
            uri: file:/rootDirectory

You can have myBean set the header Exchange.FILE_NAME to values such as:

Exchange.FILE_NAME = hello.txt => /rootDirectory/hello.txt
Exchange.FILE_NAME = foo/bye.txt => /rootDirectory/foo/bye.txt

This allows you to have a single route to write files to multiple destinations.

Writing file through the temporary directory relative to the final destination

Sometimes you need to temporarily write the files to some directory relative to the destination directory. Such a situation usually happens when some external process with limited filtering capabilities is reading from the directory you are writing to. In the example below files will be written to the /var/myapp/filesInProgress directory and after data transfer is done, they will be atomically moved to the` /var/myapp/finalDirectory `directory.

  • Java

  • XML

  • YAML

from("direct:start").
  to("file:///var/myapp/finalDirectory?tempPrefix=/../filesInProgress/");
<route>
  <from uri="direct:start"/>
  <to uri="file:///var/myapp/finalDirectory?tempPrefix=/../filesInProgress/"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: file:///var/myapp/finalDirectory
            parameters:
              tempPrefix: "/../filesInProgress/"

Avoiding reading the same file more than once (idempotent consumer)

Camel supports Idempotent Consumer directly within the component, so it will skip already processed files. This feature can be enabled by setting the idempotent=true option.

  • Java

  • XML

  • YAML

from("file://inbox?idempotent=true").to("...");
<from uri="file://inbox?idempotent=true"/>
- from:
    uri: file://inbox
    parameters:
      idempotent: true
    steps:
      - log:
          message: "${header.CamelFileName}"

Camel uses the absolute file name as the idempotent key, to detect duplicate files. You can customize this key by using an expression in the idempotentKey option. For example, to use both the name and the file size as the key

  • Java

  • XML

  • YAML

from("file://inbox?idempotent=true&idempotentKey=${file:name}-${file:size}")
    .to("bean:processInbox");
<route>
  <from uri="file://inbox?idempotent=true&amp;idempotentKey=${file:name}-${file:size}"/>
  <to uri="bean:processInbox"/>
</route>
- route:
    from:
      uri: file://inbox
      parameters:
        idempotent: true
        idempotentKey: "${file:name}-${file:size}"
      steps:
        - to:
            uri: bean:processInbox

By default, Camel uses an in-memory store for keeping track of consumed files. It uses the least recently used cache holding up to 1000 entries. You can plug in your own implementation of this store by using the idempotentRepository option using the # sign in the value to indicate it’s a referring to a bean in the Registry with the specified id.

  • Java

  • XML

  • YAML

from("file://inbox?idempotent=true&idempotentRepository=#myStore")
    .to("bean:processInbox");
<!-- define our store as a plain spring bean -->
<bean id="myStore" class="com.mycompany.MyIdempotentStore"/>

<route>
  <from uri="file://inbox?idempotent=true&amp;idempotentRepository=#myStore"/>
  <to uri="bean:processInbox"/>
</route>
- from:
    uri: file://inbox
    parameters:
      idempotent: true
      idempotentRepository: "#myStore"
    steps:
      - to:
          uri: bean:processInbox
The idempotentKey and idempotentRepository options are used only with idempotent=true (noop=true turns it on), or by the idempotent read locks (readLock=idempotent, idempotent-changed and idempotent-rename). Set without them, they do not skip any file, and the consumer logs a WARN when it is created.

Camel will log at DEBUG level if it skips a file because it has been consumed before:

DEBUG FileConsumer is idempotent and the file has been consumed before. Will skip this file: target\idempotent\report.txt

Idempotent Repository

Using a file-based idempotent repository

In this section we will use the file-based idempotent repository org.apache.camel.support.processor.idempotent.FileIdempotentRepository instead of the in-memory one that is used as default. This repository uses a first level cache to avoid reading the file repository. It will only use the file repository to store the content of the first level cache. Thereby, the repository can survive server restarts. It will load the content of the file into the first level cache upon startup. The file structure is basic as it stores the key in separate lines in the file. By default, the file store has a size limit of 32mb. When the file grows larger, Camel drops the oldest entries from the file store (1000 by default) to make room for new ones.

We declare the repository as a bean with the name of its file (fileName), and define our file consumer to use the repository with the idempotentRepository option, using #bean: to look it up in the Registry. After a restart, the files that were read before are skipped, and only the new files are read:

  • Java

  • YAML

@BindToRegistry("readFiles")
public IdempotentRepository readFiles() {
    return FileIdempotentRepository.fileIdempotentRepository("/var/data/read-files.dat");
}

@Override
public void configure() {
    from("file:/var/data/in?noop=true&idempotentRepository=#bean:readFiles")
        .log("${header.CamelFileName}");
}
- beans:
    - name: readFiles
      type: "#class:org.apache.camel.support.processor.idempotent.FileIdempotentRepository"
      properties:
        fileName: /var/data/read-files.dat
- route:
    from:
      uri: file:/var/data/in
      parameters:
        noop: true
        idempotentRepository: "#bean:readFiles"
      steps:
        - log: "${header.CamelFileName}"

The fileName property of the repository takes the file name as plain text. Use fileStore instead when you have a java.io.File.

Using a JPA based idempotent repository

In this section, we will use the JPA based idempotent repository instead of the in-memory based that is used as default.

First we need a persistence-unit in META-INF/persistence.xml where we need to use the class org.apache.camel.processor.idempotent.jpa.MessageProcessed as the model.

<persistence-unit name="idempotentDb" transaction-type="RESOURCE_LOCAL">
  <class>org.apache.camel.processor.idempotent.jpa.MessageProcessed</class>

  <properties>
    <property name="openjpa.ConnectionURL" value="jdbc:h2:./target/idempotentTest"/>
    <property name="openjpa.ConnectionDriverName" value="org.h2.Driver"/>
    <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
    <property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/>
    <property name="openjpa.Multithreaded" value="true"/>
  </properties>
</persistence-unit>

Next, we can create our JPA idempotent repository in the spring XML file as well:

XML-only: Spring bean definition for JPA-based idempotent repository
<!-- we define our jpa based idempotent repository we want to use in the file consumer -->
<bean id="jpaStore" class="org.apache.camel.processor.idempotent.jpa.JpaMessageIdRepository">
    <!-- Here we refer to the entityManagerFactory -->
    <constructor-arg index="0" ref="entityManagerFactory"/>
    <!-- This 2nd parameter is the name (= a category name).
         You can have different repositories with different names -->
    <constructor-arg index="1" value="FileConsumer"/>
</bean>

And yes then we just need to refer to the jpaStore bean in the file consumer endpoint using the idempotentRepository using the # syntax option:

  • Java

  • XML

  • YAML

from("file://inbox?idempotent=true&idempotentRepository=#jpaStore")
    .to("bean:processInbox");
<route>
  <from uri="file://inbox?idempotent=true&amp;idempotentRepository=#jpaStore"/>
  <to uri="bean:processInbox"/>
</route>
- route:
    from:
      uri: file://inbox
      parameters:
        idempotent: true
        idempotentRepository: "#jpaStore"
      steps:
        - to:
            uri: bean:processInbox

Filtering Strategies

Camel supports pluggable filtering strategies. They are described below.

The include and exclude options are regular expressions matched against the file name (case-insensitive), such as include=.*\.xml. A wildcard such as *.xml is not a valid regular expression, and the endpoint fails with a message that says so. Use antInclude and antExclude for wildcards, or includeExt and excludeExt for file extensions.

Filter using the GenericFilter

The filter option allows you to implement a custom filter in Java code by implementing the org.apache.camel.component.file.GenericFileFilter interface.

Implementing a GenericFilter

The interface has an accept method that returns a boolean. The meaning of the return values are:

  • true to include the file

  • false to skip the file.

There is also a isDirectory method on GenericFile to inform whether the file is a directory. This allows you to filter unwanted directories, to avoid traversing down unwanted directories.

Using the GenericFilter

You can then configure the endpoint with such a filter to skip certain files being processed.

In the sample we have built our own filter that skips files starting with skip in the filename:

And then we can configure our route using the filter attribute to reference our filter (using # notation) that we have defined in the spring XML file:

  • Java

  • XML

  • YAML

from("file://inbox?filter=#myFilter")
    .to("bean:processInbox");
<!-- define our filter as a plain spring bean -->
<bean id="myFilter" class="com.mycompany.MyFileFilter"/>

<route>
  <from uri="file://inbox?filter=#myFilter"/>
  <to uri="bean:processInbox"/>
</route>
- from:
    uri: file://inbox
    parameters:
      filter: "#myFilter"
    steps:
      - to:
          uri: bean:processInbox

Filtering using ANT path matcher

The ANT path matcher is based on AntPathMatcher.

The file paths are matched with the following rules:

  • ? matches one character

  • * matches zero or more characters

  • ** matches zero or more directories in a path

The antInclude and antExclude options make it easy to specify ANT style include/exclude without having to define the filter. See the URI options above for more information.

The sample below demonstrates how to use it:

  • Java

  • XML

  • YAML

from("file://inbox?antInclude=**/*.txt").to("...");
<from uri="file://inbox?antInclude=**/*.txt"/>
- from:
    uri: file://inbox
    parameters:
      antInclude: "**/*.txt"
    steps:
      - log:
          message: "${header.CamelFileName}"

Sorting Strategies

Camel supports pluggable sorting strategies. They are described below.

Sorting using Comparator

This strategy it to use the build in java.util.Comparator in Java. You can then configure the endpoint with such a comparator and have Camel sort the files before being processed.

In the sample, we have built our own comparator that just sorts by file name:

And then we can configure our route using the sorter option to reference to our sorter (mySorter) we have defined in the spring XML file:

  • Java

  • XML

  • YAML

from("file://inbox?sorter=#mySorter")
    .to("bean:processInbox");
<!-- define our sorter as a plain spring bean -->
<bean id="mySorter" class="com.mycompany.MyFileSorter"/>

<route>
  <from uri="file://inbox?sorter=#mySorter"/>
  <to uri="bean:processInbox"/>
</route>
- from:
    uri: file://inbox
    parameters:
      sorter: "#mySorter"
    steps:
      - to:
          uri: bean:processInbox

URI options can reference beans using the # syntax

In the Spring DSL route above notice that we can refer to beans in the Registry by prefixing the id with #. So writing sorter=#mySorter, will instruct Camel to go look in the Registry for a bean with the ID, mySorter.

Sorting using sortBy

Camel supports pluggable sorting strategies. This strategy uses the File Language to configure the sorting. The sortBy option is configured as follows:

sortBy=group 1;group 2;group 3;...

Where each group is separated with semicolon. In the simple situations you just use one group, so a simple example could be:

sortBy=file:name

This will sort by file name, you can reverse the order by prefixing reverse: to the group, so the sorting is now Z to A:

sortBy=reverse:file:name

As we have the full power of File Language, we can use some of the other parameters, so if we want to sort by file size, we do:

sortBy=file:length

You can configure to ignore the case, using ignoreCase: for string comparison, so if you want to use file name sorting but to ignore the case, then we do:

sortBy=ignoreCase:file:name

You can combine ignore case and reverse. However, reverse must be specified first:

sortBy=reverse:ignoreCase:file:name

In the sample below we want to sort by the last modified file, so we do:

sortBy=file:modified

And then we want to group by name as a second option, so files with the same modification time are sorted by name:

sortBy=file:modified;file:name

Now there is an issue here, can you spot it? Well, the modified timestamp of the file is too fine as it will be in milliseconds, but what if we want to sort by date only and then subgroup by name? Well, as we have the true power of File Language, we can use its date command that supports patterns. So this can be solved as:

sortBy=date:file:yyyyMMdd;file:name

Yeah, that is pretty powerful, oh by the way, you can also use reverse per group, so we could reverse the file names:

sortBy=date:file:yyyyMMdd;reverse:file:name

Using GenericFileProcessStrategy

The option processStrategy can be used to use a custom GenericFileProcessStrategy that allows you to implement your own begin, commit and rollback logic. For instance, let’s assume a system writes a file in a folder you should consume. But you should not start consuming the file before another ready file has been written as well.

So by implementing our own GenericFileProcessStrategy we can implement this as:

  • In the begin() method we can test whether the special ready file exists. The begin method returns a boolean to indicate if we can consume the file or not.

  • In the abort() method special logic can be executed in case the begin operation returned false, for example, to clean up resources etc.

  • in the commit() method we can move the actual file and also delete the ready file.

Using bridgeErrorHandler

If you want to use the Camel Error Handler to deal with any exception occurring in the file consumer, then you can enable the bridgeErrorHandler option as shown below:

Java-only: onException error handler configuration is Java DSL specific
// to handle any IOException being thrown
onException(IOException.class)
    .handled(true)
    .log("IOException occurred due: ${exception.message}")
    .transform().simple("Error ${exception.message}")
    .to("mock:error");

// this is the file route that pickup files. Notice how we bridge the consumer to use the Camel routing error handler
// the exclusiveReadLockStrategy is only configured because this is from a unit test, so we use that to simulate exceptions
from("file:target/nospace?bridgeErrorHandler=true")
    .convertBodyTo(String.class)
    .to("mock:result");

So all you have to do is to enable this option, and the error handler in the route will take it from there.

When using bridgeErrorHandler, then interceptors, OnCompletions do not apply. The Exchange is processed directly by the Camel Error Handler, and does not allow prior actions such as interceptors, onCompletion to take action.

Debug logging

This component has log level TRACE that can be helpful if you have problems.

Examples

Reading from a directory and the default move operation

By default, Camel will move any processed file into a .camel subdirectory in the directory the file was consumed from.

  • Java

  • XML

  • YAML

from("file://inputdir/?recursive=true&delete=true").to("file://outputdir");
<route>
  <from uri="file://inputdir/?recursive=true&amp;delete=true"/>
  <to uri="file://outputdir"/>
</route>
- route:
    from:
      uri: file://inputdir/
      parameters:
        recursive: true
        delete: true
      steps:
        - to:
            uri: file://outputdir

Affects the layout as follows:
before

inputdir/foo.txt
inputdir/sub/bar.txt

after

inputdir/.camel/foo.txt
inputdir/sub/.camel/bar.txt
outputdir/foo.txt
outputdir/sub/bar.txt

Read from a directory and write to another directory

  • Java

  • XML

  • YAML

from("file://inputdir/?delete=true").to("file://outputdir");
<route>
  <from uri="file://inputdir/?delete=true"/>
  <to uri="file://outputdir"/>
</route>
- route:
    from:
      uri: file://inputdir/
      parameters:
        delete: true
      steps:
        - to:
            uri: file://outputdir

Read from a directory and write to another directory using a dynamic name

  • Java

  • XML

  • YAML

from("file://inputdir/?delete=true").to("file://outputdir?fileName=copy-of-${file:name}");
<route>
  <from uri="file://inputdir/?delete=true"/>
  <to uri="file://outputdir?fileName=copy-of-${file:name}"/>
</route>
- route:
    from:
      uri: file://inputdir/
      parameters:
        delete: true
      steps:
        - to:
            uri: file://outputdir
            parameters:
              fileName: "copy-of-${file:name}"

Listen to a directory and create a message for each file dropped there. Copy the contents to the outputdir and delete the file in the inputdir.

Reading recursively from a directory and writing to another

  • Java

  • XML

  • YAML

from("file://inputdir/?recursive=true&delete=true").to("file://outputdir");
<route>
  <from uri="file://inputdir/?recursive=true&amp;delete=true"/>
  <to uri="file://outputdir"/>
</route>
- route:
    from:
      uri: file://inputdir/
      parameters:
        recursive: true
        delete: true
      steps:
        - to:
            uri: file://outputdir

Listen to a directory and create a message for each file dropped there. Copy the contents to the outputdir and delete the file in the inputdir. Will scan recursively into subdirectories. Will lay out the files in the same directory structure in the outputdir as the inputdir, including any subdirectories.

inputdir/foo.txt
inputdir/sub/bar.txt

It will result in the following output layout:

outputdir/foo.txt
outputdir/sub/bar.txt

Read from a directory and process the message in java

Java-only: inline Processor implementation
from("file://inputdir/").process(exchange -> {
    Object body = exchange.getIn().getBody();
    // do some business logic with the input body
});

The body will be a File object that points to the file that was just dropped into the inputdir directory.

Using expression for filenames

In this sample, we want to move consumed files to a backup folder using today’s date as a subfolder name:

  • Java

  • XML

  • YAML

from("file://inbox?move=backup/${date:now:yyyyMMdd}/${file:name}").to("...");
<route>
  <from uri="file://inbox?move=backup/${date:now:yyyyMMdd}/${file:name}"/>
  <to uri="..."/>
</route>
- route:
    from:
      uri: file://inbox
      parameters:
        move: "backup/${date:now:yyyyMMdd}/${file:name}"
      steps:
        - to:
            uri: "..."

See File Language for more samples.