Apache Camel File component: polling, locking and writing files

The File component turns a directory into a source or a destination for Camel routes. Its defaults decide where processed files go, what happens to a file that fails, and whether a half-written file is read. This page explains how the polling consumer works, then runs each important option and trap against real files.

Contents

How the File component reads and writes files

The File component connects a Camel route to a directory. Used in from("file:inbox"), it is a consumer that turns each file in the directory into a message. Used in to("file:outbox"), it is a producer that writes the message body to a file. The endpoint URI has the form file:directoryName?option=value&..., and the options decide almost everything the component does.

The consumer is a scheduled polling consumer. It does not watch the directory for events. Instead, one thread per route works in a loop:

  1. Wait initialDelay milliseconds (1000 by default) before the first poll, and delay milliseconds (500 by default) between polls.
  2. List the directory, drop the files that the filter options reject, sort what is left if sortBy is set, and cut the list to maxMessagesPerPoll.
  3. For each file, try to take a read lock, create an exchange whose body is a GenericFile, and run the route.
  4. When the route finishes, commit or roll back the file: on success move it, delete it or leave it; on failure leave it where it is, or move it to moveFailed.

The body is a handle to the file, not its content. Camel reads the bytes only when something converts the body, for example getBody(String.class) or a splitter that asks for an InputStream. That is why the same route can process a 20 MB file line by line with a small heap, as a later section shows.

The options that matter most, by stage
StageOptionsDefault
PollinginitialDelay, delay, maxMessagesPerPoll1000 ms, 500 ms, no limit
Choosing filesinclude, exclude, includeExt, antInclude, filter, recursive, sortByAll non-hidden files in the directory itself
Read lockreadLock, doneFileNamenone
Before processingpreMoveNot moved
After successmove, delete, noopMoved to .camel
After failuremoveFailedLeft in place and polled again
WritingfileName, fileExist, tempFileName, doneFileName, charsetName from the CamelFileName header, fileExist=Override

The FTP, FTPS and SFTP components in camel-ftp are built on the same base classes, so nearly every option on this page works for remote directories too. The examples are complete programs for Camel 4.23 on Java 21, using camel-file with a plain DefaultCamelContext. Each one turns Camel's logging off so that the output shows only what the program prints, and each one waits for the route with a NotifyBuilder, which completes when a given number of exchanges are done.

Polling a directory

Two small order files are enough to see what the consumer hands to the route, and where the files end up afterwards:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class FirstPoll {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        Path base = Files.createTempDirectory("camel-file");
        Path inbox = Files.createDirectory(base.resolve("inbox"));
        Files.writeString(inbox.resolve("order-1.txt"), "2 x book");
        Files.writeString(inbox.resolve("order-2.txt"), "1 x pen, 3 x pencil");

        CamelContext context = new DefaultCamelContext();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("file:" + inbox + "?initialDelay=0&sortBy=file:name")
                        .process(exchange -> {
                            var in = exchange.getMessage();
                            System.out.println("body type : "
                                    + in.getBody().getClass().getSimpleName());
                            System.out.println("file name : "
                                    + in.getHeader(Exchange.FILE_NAME));
                            System.out.println("length    : "
                                    + in.getHeader(Exchange.FILE_LENGTH) + " bytes");
                            System.out.println("content   : " + in.getBody(String.class));
                            System.out.println("still in inbox while processing: "
                                    + Files.exists(inbox.resolve(
                                            in.getHeader(Exchange.FILE_NAME, String.class))));
                            System.out.println();
                        });
            }
        });
        NotifyBuilder twoDone = new NotifyBuilder(context).whenDone(2).create();
        context.start();
        System.out.println("both files done: " + twoDone.matches(10, TimeUnit.SECONDS));
        context.close();

        System.out.println("Files after the route ran:");
        try (Stream<Path> files = Files.walk(base)) {
            files.filter(Files::isRegularFile).sorted()
                    .forEach(f -> System.out.println("  " + base.relativize(f)));
        }
    }
}
Output
body type : GenericFile
file name : order-1.txt
length    : 8 bytes
content   : 2 x book
still in inbox while processing: true

body type : GenericFile
file name : order-2.txt
length    : 19 bytes
content   : 1 x pen, 3 x pencil
still in inbox while processing: true

both files done: true
Files after the route ran:
  inbox/.camel/order-1.txt
  inbox/.camel/order-2.txt
  • The body type is GenericFile, the handle described above. getBody(String.class) then read the content, 2 x book and 1 x pen, 3 x pencil, using the platform charset unless the endpoint sets charset.
  • The CamelFileName and CamelFileLength headers came from the file system: 8 and 19 bytes. Other headers carry the absolute path, the parent directory and the last-modified time.
  • Both files were still in the inbox while the route ran. Camel moves a file only after the exchange completes.
  • With no move, delete or noop option, Camel moved both files to a hidden .camel subdirectory. That default often surprises people who expect the file to stay where it was, or to disappear.

initialDelay=0 starts the first poll at once, which keeps the examples fast. sortBy=file:name fixes the order: without it, files arrive in the order the operating system lists them, which is not alphabetical on most file systems.

Move, delete or leave the file

A real inbox needs to say what happened to each file. This program sends three orders through one route, where the second order is invalid and fails, and a fourth file through a route that deletes what it processes:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class AfterProcessing {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        Path base = Files.createTempDirectory("camel-file");
        Path orders = Files.createDirectory(base.resolve("orders"));
        Path tmp = Files.createDirectory(base.resolve("tmp"));
        Files.writeString(orders.resolve("order-1.txt"), "2 x book, 1 x lamp");
        Files.writeString(orders.resolve("order-2.txt"), "INVALID");
        Files.writeString(orders.resolve("order-3.txt"), "1 x pen");
        Files.writeString(tmp.resolve("scratch.txt"), "throw me away");

        CamelContext context = new DefaultCamelContext();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("file:" + orders + "?initialDelay=0&sortBy=file:name"
                        + "&preMove=.inprogress"
                        + "&move=done/${file:name.noext}-${header.items}items.${file:ext}"
                        + "&moveFailed=.error")
                        .process(exchange -> {
                            String body = exchange.getMessage().getBody(String.class);
                            System.out.println("processing " + exchange.getMessage()
                                    .getHeader("CamelFileName") + ": " + body);
                            if (body.contains("INVALID")) {
                                throw new IllegalArgumentException("bad order");
                            }
                            exchange.getMessage().setHeader("items", body.split(",").length);
                        });
                from("file:" + tmp + "?initialDelay=0&delete=true")
                        .to("log:deleted");
            }
        });
        NotifyBuilder allDone = new NotifyBuilder(context).whenDone(4).create();
        context.start();
        allDone.matches(10, TimeUnit.SECONDS);
        context.close();

        System.out.println("Files after the routes ran:");
        try (Stream<Path> files = Files.walk(base)) {
            files.filter(Files::isRegularFile).sorted()
                    .forEach(f -> System.out.println("  " + base.relativize(f)));
        }
    }
}
Output
processing order-1.txt: 2 x book, 1 x lamp
processing order-2.txt: INVALID
processing order-3.txt: 1 x pen
Files after the routes ran:
  orders/.inprogress/.error/order-2.txt
  orders/done/order-1-2items.txt
  orders/done/order-3-1items.txt
  • move takes a Simple expression, so the archived name can include values computed by the route. Order 1 had two items and became done/order-1-2items.txt; order 3 had one and became done/order-3-1items.txt.
  • Order 2 threw an exception, so Camel applied moveFailed instead of move.
  • scratch.txt does not appear at all: the second route used delete=true.

The failed file shows a trap. preMove=.inprogress moved each file into .inprogress before the route ran, and moveFailed=.error was then resolved from there, giving orders/.inprogress/.error/order-2.txt. move=done/... is resolved from the starting directory, so the two options behave differently. Running the same program with moveFailed=../.error puts the failed file in orders/.error. preMove is useful for showing which files are being worked on, but check where moveFailed lands before relying on it.

What happens to a file after the route
OptionsOn successOn failure
NoneMoved to .camelLeft in place, polled again
move=exprMoved to the expression's pathLeft in place, polled again
delete=trueDeletedLeft in place, polled again
noop=trueLeft in place, remembered as processedLeft in place, polled again
Any of the above with moveFailed=exprAs aboveMoved to the expression's path

A failing file is read again and again

When the route fails and no moveFailed is set, the file stays in the inbox, and the next poll picks it up again. A file that can never be processed is retried forever. This program runs the same failing route twice, once without and once with moveFailed, and polls every 200 ms:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class RetryTrap {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        run("without moveFailed", "");
        run("with moveFailed=.error", "&moveFailed=.error");
    }

    static void run(String label, String extraOptions) throws Exception {
        Path inbox = Files.createTempDirectory("inbox");
        Files.writeString(inbox.resolve("broken.txt"), "INVALID");
        AtomicInteger attempts = new AtomicInteger();

        CamelContext context = new DefaultCamelContext();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("file:" + inbox + "?initialDelay=0&delay=200" + extraOptions)
                        .process(exchange -> {
                            System.out.println("  attempt " + attempts.incrementAndGet()
                                    + " at " + exchange.getMessage().getHeader("CamelFileName"));
                            throw new IllegalStateException("cannot parse");
                        });
            }
        });
        System.out.println(label + ":");
        NotifyBuilder threeFailures = new NotifyBuilder(context).whenFailed(3).create();
        context.start();
        boolean reachedThree = threeFailures.matches(2, TimeUnit.SECONDS);
        context.close();
        System.out.println("  three failures within 2 seconds: " + reachedThree);
        System.out.println("  broken.txt still in the inbox: "
                + Files.exists(inbox.resolve("broken.txt")));
        System.out.println("  broken.txt in .error: "
                + Files.exists(inbox.resolve(".error/broken.txt")));
    }
}
Output
without moveFailed:
  attempt 1 at broken.txt
  attempt 2 at broken.txt
  attempt 3 at broken.txt
  three failures within 2 seconds: true
  broken.txt still in the inbox: true
  broken.txt in .error: false
with moveFailed=.error:
  attempt 1 at broken.txt
  three failures within 2 seconds: false
  broken.txt still in the inbox: false
  broken.txt in .error: true
  • Without moveFailed, the route ran three times in well under two seconds, and the file was still in the inbox when the program stopped. In production this is a log full of the same stack trace, every half second, for as long as the file exists.
  • With moveFailed=.error, there was one attempt. The file then went to .error, where someone can look at it, and the inbox was free for other files.

Retrying is sometimes the right behaviour, for example when the route calls a service that is briefly down. In that case, retry inside the route with the error handler's redelivery options, as the Camel error handling page shows, and keep moveFailed for the files that still fail after the retries.

Writing files

The producer writes the message body to a file in the endpoint's directory. Writing to one file name several times shows each fileExist setting, and the rest of the program covers subdirectories, temporary names and done files:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class WritingFiles {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        Path out = Files.createTempDirectory("out");
        CamelContext context = new DefaultCamelContext();
        context.start();
        ProducerTemplate template = context.createProducerTemplate();
        String dir = "file:" + out;

        template.sendBodyAndHeader(dir, "first\n", Exchange.FILE_NAME, "report.txt");
        template.sendBodyAndHeader(dir, "second\n", Exchange.FILE_NAME, "report.txt");
        System.out.println("default (Override): " + read(out, "report.txt"));

        template.sendBodyAndHeader(dir + "?fileExist=Append", "third\n",
                Exchange.FILE_NAME, "report.txt");
        System.out.println("Append            : " + read(out, "report.txt"));

        template.sendBodyAndHeader(dir + "?fileExist=Ignore", "fourth\n",
                Exchange.FILE_NAME, "report.txt");
        System.out.println("Ignore            : " + read(out, "report.txt"));

        try {
            template.sendBodyAndHeader(dir + "?fileExist=Fail", "fifth\n",
                    Exchange.FILE_NAME, "report.txt");
        } catch (CamelExecutionException e) {
            System.out.println("Fail              : " + e.getCause().getClass().getSimpleName());
        }

        Exchange sent = template.send(dir + "?tempFileName=${file:name}.part"
                + "&doneFileName=${file:name}.done", exchange -> {
                    exchange.getMessage().setBody("id,total\n1,9.99\n");
                    exchange.getMessage().setHeader(Exchange.FILE_NAME,
                            "2026/11/orders.csv");
                });
        String produced = sent.getMessage().getHeader(Exchange.FILE_NAME_PRODUCED, String.class);
        System.out.println("CamelFileNameProduced ends with: "
                + out.relativize(Path.of(produced)));

        Exchange unnamed = template.send(dir, exchange -> exchange.getMessage().setBody("x"));
        Path written = Path.of(unnamed.getMessage()
                .getHeader(Exchange.FILE_NAME_PRODUCED, String.class));
        System.out.println("no file name given, so the name is the exchange id: "
                + written.getFileName().toString().equals(unnamed.getExchangeId()));
        Files.delete(written);
        context.close();

        System.out.println("Files written:");
        try (Stream<Path> files = Files.walk(out)) {
            files.filter(Files::isRegularFile).sorted()
                    .forEach(f -> System.out.println("  " + out.relativize(f)));
        }
    }

    static String read(Path dir, String name) throws Exception {
        return Files.readString(dir.resolve(name)).replace("\n", "\\n");
    }
}
Output
default (Override): second\n
Append            : second\nthird\n
Ignore            : second\nthird\n
Fail              : GenericFileOperationFailedException
CamelFileNameProduced ends with: 2026/11/orders.csv
no file name given, so the name is the exchange id: true
Files written:
  2026/11/orders.csv
  2026/11/orders.csv.done
  report.txt
  • The second write replaced the first without a warning. fileExist=Override is the default, so two messages with the same CamelFileName silently lose data.
  • Append added third to the end, Ignore left the file unchanged and reported success, and Fail threw GenericFileOperationFailedException, wrapped in a CamelExecutionException by the ProducerTemplate.
  • A file name with slashes, 2026/11/orders.csv, created the missing directories, because autoCreate is on by default. Camel reported the full path it wrote in the CamelFileNameProduced header.
  • tempFileName=${file:name}.part wrote the content to orders.csv.part and renamed it when the write was complete, so the .part file is gone. A program polling that directory never sees a half-written orders.csv.
  • doneFileName wrote an empty orders.csv.done after the data file, a signal that the next section uses on the reading side.
  • Without a CamelFileName header or a fileName option, Camel named the file after the exchange id, a unique string that differs on every run. The program deleted it to keep the listing short.

The file name can also be set on the endpoint, as in file:out?fileName=report-${date:now:yyyyMMdd}.txt, using the same Simple language as move.

Files that are still being written

The consumer has no way to know that another program is still writing a file, unless something tells it. Here a writer creates upload.csv with one row, waits one second, then adds two more rows, closes the file and creates upload.csv.done. The program runs three consumers against that writer:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class ReadLock {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        poll("readLock=none (the default)", "");
        poll("doneFileName=${file:name}.done", "&doneFileName=${file:name}.done");
        poll("readLock=changed", "&readLock=changed&readLockCheckInterval=1500");
    }

    // another program is still writing upload.csv when the poll starts
    static void poll(String label, String options) throws Exception {
        Path inbox = Files.createTempDirectory("inbox");
        Path upload = inbox.resolve("upload.csv");
        Writer writer = Files.newBufferedWriter(upload);
        writer.write("row 1\n");
        writer.flush();

        CamelContext context = new DefaultCamelContext();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("file:" + inbox + "?initialDelay=0&delay=200" + options)
                        .process(e -> System.out.println("  read: " + e.getMessage()
                                .getBody(String.class).strip().replace("\n", " | ")));
            }
        });
        System.out.println(label + ":");
        NotifyBuilder done = new NotifyBuilder(context).whenDone(1).create();
        context.start();
        Thread.sleep(1000);
        writer.write("row 2\nrow 3\n");
        writer.close();
        Files.createFile(inbox.resolve("upload.csv.done"));
        System.out.println("  writer finished");
        done.matches(10, TimeUnit.SECONDS);
        context.close();
    }
}
Output
readLock=none (the default):
  read: row 1
  writer finished
doneFileName=${file:name}.done:
  writer finished
  read: row 1 | row 2 | row 3
readLock=changed:
  writer finished
  read: row 1 | row 2 | row 3
  • With the default readLock=none, the route read the file on the first poll and got only row 1, before the writer finished. Rows 2 and 3 were never processed.
  • With doneFileName=${file:name}.done, the consumer ignored upload.csv until upload.csv.done appeared, and then read all three rows. Camel deletes the done file along with the data file.
  • With readLock=changed, Camel compared the file's length and modification time between checks, and took the file only once they had stopped changing. It also got all three rows.

A done file, or a writer that uses a temporary name and renames at the end, is the reliable way: the reader waits for a signal that only appears when the data is complete. readLock=changed needs no help from the writer, but it guesses. It always waits at least one check interval, and a writer that pauses for longer than readLockCheckInterval looks finished. Here the interval was 1500 ms, longer than the writer's one-second pause.

Read lock strategies
readLockHow it decides the file is readyBest for
none (default)It does not checkWriters that rename into the directory, or a done file
markerFileCreates name.camelLock so other Camel consumers skip the fileSeveral Camel instances on one directory
changedLength and modification time stay the same between checksWriters you cannot change
fileLockjava.nio.channels.FileLockLocal file systems; avoid it on network shares without distributed locks
renameRenaming the file succeedsSystems where an open file cannot be renamed
idempotentClaims the file name in an idempotent repositoryClusters sharing a directory and a repository

Choosing which files to read

Six routes read the same directory, each with a different filter option. The directory holds files with mixed case, a temporary file, a hidden file and a subdirectory, so every option has something to reject. noop=true keeps the files in place so that each route sees all of them:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.file.GenericFile;
import org.apache.camel.component.file.GenericFileFilter;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class Filtering {

    // accepts directories, so that recursive polling still walks into them
    static class SmallFiles implements GenericFileFilter<Object> {
        @Override
        public boolean accept(GenericFile<Object> file) {
            return file.isDirectory() || file.getFileLength() < 10;
        }
    }

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        Path in = Files.createTempDirectory("in");
        Files.createDirectories(in.resolve("2026/11"));
        Files.writeString(in.resolve("a.csv"), "1,2,3");
        Files.writeString(in.resolve("B.CSV"), "4,5,6,7,8,9");
        Files.writeString(in.resolve("c.txt"), "hello");
        Files.writeString(in.resolve("d.csv.tmp"), "half");
        Files.writeString(in.resolve(".hidden.csv"), "x");
        Files.writeString(in.resolve("2026/11/e.csv"), "10,11");

        Map<String, String> options = new TreeMap<>();
        options.put("1 include=.*\\.csv", "include=.*\\.csv");
        options.put("2 includeExt=csv,txt", "includeExt=csv,txt");
        options.put("3 exclude=.*\\.tmp", "exclude=.*\\.tmp");
        options.put("4 recursive=true&antInclude=**/*.csv",
                "recursive=true&antInclude=**/*.csv");
        options.put("5 recursive=true&filter=#small", "recursive=true&filter=#small");
        options.put("6 maxMessagesPerPoll=2", "maxMessagesPerPoll=2&delay=100");

        Map<String, List<String>> seen = new TreeMap<>();
        CamelContext context = new DefaultCamelContext();
        context.getRegistry().bind("small", new SmallFiles());
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                options.forEach((label, query) -> {
                    List<String> names = new ArrayList<>();
                    seen.put(label, names);
                    from("file:" + in + "?noop=true&initialDelay=0"
                            + "&sortBy=ignoreCase:file:name&" + query)
                            .process(e -> {
                                String name = e.getMessage().getHeader("CamelFileName",
                                        String.class);
                                if (label.contains("maxMessagesPerPoll")) {
                                    int index = e.getProperty("CamelBatchIndex", Integer.class);
                                    name += " " + (index + 1) + "/"
                                            + e.getProperty("CamelBatchSize");
                                }
                                names.add(name);
                            });
                });
            }
        });
        NotifyBuilder all = new NotifyBuilder(context).whenDone(18).create();
        context.start();
        System.out.println("all routes done: " + all.matches(10, TimeUnit.SECONDS));
        context.close();
        seen.forEach((label, names) -> System.out.printf("%-40s %s%n", label, names));
    }
}
Output
all routes done: true
1 include=.*\.csv                        [a.csv, B.CSV]
2 includeExt=csv,txt                     [a.csv, B.CSV, c.txt]
3 exclude=.*\.tmp                        [a.csv, B.CSV, c.txt]
4 recursive=true&antInclude=**/*.csv     [2026/11/e.csv, a.csv]
5 recursive=true&filter=#small           [2026/11/e.csv, a.csv, c.txt, d.csv.tmp]
6 maxMessagesPerPoll=2                   [a.csv 1/2, d.csv.tmp 2/2, B.CSV 1/2, c.txt 2/2]
  • include and exclude are regular expressions matched against the file name, ignoring case, so B.CSV matched .*\.csv. The hidden .hidden.csv never appears: files and directories starting with a dot are skipped unless includeHiddenFiles or includeHiddenDirs is set.
  • includeExt=csv,txt is the simpler form for extensions. d.csv.tmp has the extension tmp, so it was left out.
  • Route 4 is the only one that found 2026/11/e.csv together with a pattern: antInclude is an Ant path pattern, and recursive=true lets the consumer walk into subdirectories. CamelFileName then holds the path relative to the starting directory. Unlike include, Ant patterns are case-sensitive by default (antFilterCaseSensitive=true), so B.CSV was missed.
  • Route 5 used a GenericFileFilter bean, bound in the registry as small, which accepted files under 10 bytes. B.CSV, at 11 bytes, was rejected. The filter must accept directories as well, or recursive finds nothing in them.
  • maxMessagesPerPoll=2 split four files into two polls of two, numbered from the CamelBatchIndex and CamelBatchSize properties. The pairs are not in name order: the limit is applied while scanning, before the sort, so each poll took the first two files the file system listed and then sorted those. Set eagerMaxMessagesPerPoll=false to scan everything and sort before the limit.

Each route needs its own sortBy, here ignoreCase:file:name. sortBy takes File language expressions such as file:modified or file:length, accepts a reverse: prefix, and can sort by several keys separated by ;.

Reading each file only once: idempotent consumers

With noop=true, files stay in the directory, so Camel needs another way to avoid reading them on every poll. It turns on idempotent=true, which records each file's key in a repository and skips files whose key is already there. The key decides what counts as the same file, and the repository decides how long Camel remembers. This program tests both with a price list that is rewritten while two routes run:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.IdempotentRepository;
import org.apache.camel.support.processor.idempotent.FileIdempotentRepository;
import org.slf4j.LoggerFactory;

public class Idempotent {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        Path feed = Files.createTempDirectory("feed");
        Path prices = feed.resolve("prices.csv");
        Files.writeString(prices, "book,10");

        System.out.println("Part 1: the same file is changed while the routes run");
        CamelContext context = new DefaultCamelContext();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("file:" + feed + "?noop=true&initialDelay=0&delay=100")
                        .routeId("default-key")
                        .process(e -> System.out.println("  default-key read: "
                                + e.getMessage().getBody(String.class)));
                from("file:" + feed + "?noop=true&initialDelay=300&delay=100"
                        + "&idempotentKey=${file:name}-${file:size}-${file:modified}")
                        .routeId("content-key")
                        .process(e -> System.out.println("  content-key read: "
                                + e.getMessage().getBody(String.class)));
            }
        });
        NotifyBuilder firstRead = new NotifyBuilder(context).whenDone(2).create();
        context.start();
        firstRead.matches(5, TimeUnit.SECONDS);

        NotifyBuilder reRead = new NotifyBuilder(context).fromRoute("content-key")
                .whenDone(1).create();
        System.out.println("  (prices.csv rewritten)");
        Files.writeString(prices, "book,12");
        Files.setLastModifiedTime(prices, FileTime.from(Instant.now().plusSeconds(5)));
        System.out.println("  content-key saw the change: " + reRead.matches(5, TimeUnit.SECONDS));
        Thread.sleep(500); // five more polls for default-key
        context.close();

        System.out.println("Part 2: a FileIdempotentRepository survives a restart");
        Path store = Files.createTempFile("processed", ".dat");
        for (int run = 1; run <= 2; run++) {
            IdempotentRepository repo =
                    FileIdempotentRepository.fileIdempotentRepository(store.toFile());
            CamelContext app = new DefaultCamelContext();
            app.getRegistry().bind("processed", repo);
            int thisRun = run;
            app.addRoutes(new RouteBuilder() {
                @Override
                public void configure() {
                    from("file:" + feed + "?noop=true&initialDelay=0"
                            + "&idempotentRepository=#processed&idempotentKey=${file:name}")
                            .process(e -> System.out.println("  run " + thisRun + " read "
                                    + e.getMessage().getHeader("CamelFileName")));
                }
            });
            app.start();
            Thread.sleep(1000);
            app.close();
            System.out.println("  after run " + run + ", the store holds: "
                    + Files.readAllLines(store));
        }
    }
}
Output
Part 1: the same file is changed while the routes run
  default-key read: book,10
  content-key read: book,10
  (prices.csv rewritten)
  content-key read: book,12
  content-key saw the change: true
Part 2: a FileIdempotentRepository survives a restart
  run 1 read prices.csv
  after run 1, the store holds: [prices.csv]
  after run 2, the store holds: [prices.csv]
  • The default key is the file's absolute path. When prices.csv changed from book,10 to book,12, the path stayed the same, so default-key never read the new price, although it polled several more times.
  • content-key used idempotentKey=${file:name}-${file:size}-${file:modified}. The new modification time made a new key, so it read book,12. The program set the modification time five seconds ahead because some file systems store it in whole seconds, and two writes within one second could otherwise produce the same key.
  • The default repository is a MemoryIdempotentRepository holding the last 1000 keys, so a restart forgets everything and reads every file again. In part 2, a FileIdempotentRepository wrote prices.csv to a store file in run 1, and run 2 found it there and read nothing.

For a cluster where several nodes poll a shared directory, use a shared repository, such as JdbcMessageIdRepository from camel-sql, together with readLock=idempotent, so that one node claims a file before the others can.

Large files: split and stream

Converting the body to a String loads the whole file into memory. For large files, the splitter can read the file as a stream and send one line at a time through the route. This program writes a 2,000,000-line CSV file of about 20 MB and sums one column with a 32 MB heap (-Xmx32m):

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class SplitLines {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        Path inbox = Files.createTempDirectory("inbox");
        try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(
                inbox.resolve("payments.csv")))) {
            out.println("id,amount");
            for (int i = 1; i <= 2000000; i++) {
                out.println(i + "," + (i % 100));
            }
        }
        System.out.println("file size: " + Files.size(inbox.resolve("payments.csv")) + " bytes");
        AtomicLong lines = new AtomicLong();
        AtomicLong total = new AtomicLong();

        CamelContext context = new DefaultCamelContext();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("file:" + inbox + "?initialDelay=0&delete=true")
                        .split(body().tokenize("\n")).streaming()
                            .filter(simple("${exchangeProperty.CamelSplitIndex} > 0"))
                            .process(e -> {
                                lines.incrementAndGet();
                                total.addAndGet(Long.parseLong(
                                        e.getMessage().getBody(String.class).split(",")[1]));
                            })
                        .end()
                        .end()
                        .process(e -> System.out.println("body type after the split: "
                                + e.getMessage().getBody().getClass().getSimpleName()));
            }
        });
        NotifyBuilder done = new NotifyBuilder(context).whenDone(1).create();
        context.start();
        done.matches(60, TimeUnit.SECONDS);
        context.close();
        System.out.println("data lines: " + lines.get() + ", sum of amounts: " + total.get());
        System.out.println("max heap: " + Runtime.getRuntime().maxMemory() / (1024 * 1024)
                + " MB");
        System.out.println("file deleted: " + !Files.exists(inbox.resolve("payments.csv")));
    }
}
Output
file size: 20688906 bytes
body type after the split: GenericFile
data lines: 2000000, sum of amounts: 99000000
max heap: 32 MB
file deleted: true
  • All 2,000,000 data lines were processed, and the sum is 99,000,000, with a maximum heap of 32 MB, less than twice the file size.
  • After the split, the body is still the GenericFile: the splitter read the file through a stream and never replaced the body with its content.
  • The filter skipped line 0, the header, using the CamelSplitIndex property that the splitter sets on each part.

The same route with convertBodyTo(String.class) before a split without streaming() stopped with OutOfMemoryError: Java heap space at the same heap size. streaming() matters because without it the splitter collects all parts in a list before sending the first one. The Camel splitter page covers splitting in depth, and handling large files shows the same problem in plain Java.

Choosing options for a file route

Common situations and the options that fit them
SituationOptions
Process each file once and keep an archivemove=done/${file:name} plus moveFailed=.error
Process and throw awaydelete=true plus moveFailed=.error
Read files that other systems ownnoop=true with an idempotentKey that includes size or modification time, and a FileIdempotentRepository
Another program writes the filesdoneFileName if the writer can create one, otherwise readLock=changed
Camel writes files that another program readstempFileName or doneFileName on the producer
Output must not overwrite earlier filesA unique fileName, or fileExist=Fail
Thousands of files in the inbox at startupmaxMessagesPerPoll, with eagerMaxMessagesPerPoll=false if order matters
Files larger than a few MBsplit(body().tokenize("\n")).streaming(), never convertBodyTo(String.class)
Several Camel instances on one directoryreadLock=idempotent with a shared database repository

Most production problems with file routes come from four defaults shown on this page: processed files go to .camel, failed files are read again forever, a file is read even while it is still being written, and the producer overwrites existing files. Set those four options deliberately on every route. For the basics of routes and exchanges, see the Camel introduction; to start routes on a schedule rather than when files appear, see Camel timer.