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 Polling a directory Move, delete or leave the file A failing file is read again and again Writing files Files that are still being written Choosing which files to read Reading each file only once: idempotent consumers Large files: split and stream Choosing options for a file route
How the File component reads and writes files
The File component connects a Camel route to a directory. Used in from("file:inbox")to("file:outbox")file:directoryName?option=value&...
The consumer is a scheduled polling consumer. It does not watch the directory for events. Instead, one thread per route works in a loop:
- Wait
milliseconds (1000 by default) before the first poll, andinitialDelay milliseconds (500 by default) between polls.delay - List the directory, drop the files that the filter options reject, sort what is left if
is set, and cut the list tosortBy .maxMessagesPerPoll - For each file, try to take a read lock, create an exchange whose body is a
, and run the route.GenericFile - 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)InputStream
| Stage | Options | Default |
|---|---|---|
| Polling | initialDelaydelaymaxMessagesPerPoll | 1000 ms, 500 ms, no limit |
| Choosing files | includeexcludeincludeExtantIncludefilterrecursivesortBy | All non-hidden files in the directory itself |
| Read lock | readLockdoneFileName | none |
| Before processing | preMove | Not moved |
| After success | movedeletenoop | Moved to .camel |
| After failure | moveFailed | Left in place and polled again |
| Writing | fileNamefileExisttempFileNamedoneFileNamecharset | Name from the CamelFileNamefileExist=Override |
The FTP, FTPS and SFTP components in camel-ftpcamel-fileDefaultCamelContextNotifyBuilder
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:
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)));
}
}
}
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
, the handle described above.GenericFile then read the content,getBody(String.class) and2 x book , using the platform charset unless the endpoint sets1 x pen, 3 x pencil .charset - The
andCamelFileName headers came from the file system: 8 and 19 bytes. Other headers carry the absolute path, the parent directory and the last-modified time.CamelFileLength - Both files were still in the inbox while the route ran. Camel moves a file only after the exchange completes.
- With no
,move ordelete option, Camel moved both files to a hiddennoop subdirectory. That default often surprises people who expect the file to stay where it was, or to disappear..camel
initialDelay=0sortBy=file:name
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:
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)));
}
}
}
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
takes a Simple expression, so the archived name can include values computed by the route. Order 1 had two items and becamemove ; order 3 had one and becamedone/order-1-2items.txt .done/order-3-1items.txt- Order 2 threw an exception, so Camel applied
instead ofmoveFailed .move does not appear at all: the second route usedscratch.txt .delete=true
The failed file shows a trap. preMove=.inprogress.inprogressmoveFailed=.errororders/.inprogress/.error/order-2.txtmove=done/...moveFailed=../.errororders/.errorpreMovemoveFailed
| Options | On success | On failure |
|---|---|---|
| None | Moved to .camel | Left in place, polled again |
move=expr | Moved to the expression's path | Left in place, polled again |
delete=true | Deleted | Left in place, polled again |
noop=true | Left in place, remembered as processed | Left in place, polled again |
Any of the above with moveFailed=expr | As above | Moved to the expression's path |
A failing file is read again and again
When the route fails and no moveFailedmoveFailed
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")));
}
}
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
, 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.moveFailed - With
, there was one attempt. The file then went tomoveFailed=.error , where someone can look at it, and the inbox was free for other files..error
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 moveFailed
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
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");
}
}
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.
is the default, so two messages with the samefileExist=Override silently lose data.CamelFileName addedAppend to the end,third left the file unchanged and reported success, andIgnore threwFail , wrapped in aGenericFileOperationFailedException by theCamelExecutionException .ProducerTemplate- A file name with slashes,
, created the missing directories, because2026/11/orders.csv is on by default. Camel reported the full path it wrote in theautoCreate header.CamelFileNameProduced wrote the content totempFileName=${file:name}.part and renamed it when the write was complete, so theorders.csv.part file is gone. A program polling that directory never sees a half-written.part .orders.csv wrote an emptydoneFileName after the data file, a signal that the next section uses on the reading side.orders.csv.done- Without a
header or aCamelFileName 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.fileName
The file name can also be set on the endpoint, as in file:out?fileName=report-${date:now:yyyyMMdd}.txtmove
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.csvupload.csv.done
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();
}
}
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
, the route read the file on the first poll and got onlyreadLock=none , before the writer finished. Rows 2 and 3 were never processed.row 1 - With
, the consumer ignoreddoneFileName=${file:name}.done untilupload.csv appeared, and then read all three rows. Camel deletes the done file along with the data file.upload.csv.done - With
, 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.readLock=changed
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=changedreadLockCheckInterval
| readLock | How it decides the file is ready | Best for |
|---|---|---|
none | It does not check | Writers that rename into the directory, or a done file |
markerFile | Creates name.camelLock | Several Camel instances on one directory |
changed | Length and modification time stay the same between checks | Writers you cannot change |
fileLock | java.nio.channels.FileLock | Local file systems; avoid it on network shares without distributed locks |
rename | Renaming the file succeeds | Systems where an open file cannot be renamed |
idempotent | Claims the file name in an idempotent repository | Clusters 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
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));
}
}
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]
andinclude are regular expressions matched against the file name, ignoring case, soexclude matchedB.CSV . The hidden.*\.csv never appears: files and directories starting with a dot are skipped unless.hidden.csv orincludeHiddenFiles is set.includeHiddenDirs is the simpler form for extensions.includeExt=csv,txt has the extensiond.csv.tmp , so it was left out.tmp- Route 4 is the only one that found
together with a pattern:2026/11/e.csv is an Ant path pattern, andantInclude lets the consumer walk into subdirectories.recursive=true then holds the path relative to the starting directory. UnlikeCamelFileName , Ant patterns are case-sensitive by default (include ), soantFilterCaseSensitive=true was missed.B.CSV - Route 5 used a
bean, bound in the registry asGenericFileFilter , which accepted files under 10 bytes.small , at 11 bytes, was rejected. The filter must accept directories as well, orB.CSV finds nothing in them.recursive split four files into two polls of two, numbered from themaxMessagesPerPoll=2 andCamelBatchIndex 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. SetCamelBatchSize to scan everything and sort before the limit.eagerMaxMessagesPerPoll=false
Each route needs its own sortByignoreCase:file:namesortByfile:modifiedfile:lengthreverse:;
Reading each file only once: idempotent consumers
With noop=trueidempotent=true
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));
}
}
}
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
changed fromprices.csv tobook,10 , the path stayed the same, sobook,12 never read the new price, although it polled several more times.default-key usedcontent-key . The new modification time made a new key, so it readidempotentKey=${file:name}-${file:size}-${file:modified} . 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.book,12- The default repository is a
holding the last 1000 keys, so a restart forgets everything and reads every file again. In part 2, aMemoryIdempotentRepository wroteFileIdempotentRepository to a store file in run 1, and run 2 found it there and read nothing.prices.csv
For a cluster where several nodes poll a shared directory, use a shared repository, such as JdbcMessageIdRepositorycamel-sqlreadLock=idempotent
Large files: split and stream
Converting the body to a String-Xmx32m
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")));
}
}
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
: the splitter read the file through a stream and never replaced the body with its content.GenericFile - The
skipped line 0, the header, using thefilter property that the splitter sets on each part.CamelSplitIndex
The same route with convertBodyTo(String.class)streaming()OutOfMemoryError: Java heap spacestreaming()
Choosing options for a file route
| Situation | Options |
|---|---|
| Process each file once and keep an archive | move=done/${file:name}moveFailed=.error |
| Process and throw away | delete=truemoveFailed=.error |
| Read files that other systems own | noop=trueidempotentKeyFileIdempotentRepository |
| Another program writes the files | doneFileNamereadLock=changed |
| Camel writes files that another program reads | tempFileNamedoneFileName |
| Output must not overwrite earlier files | A unique fileNamefileExist=Fail |
| Thousands of files in the inbox at startup | maxMessagesPerPolleagerMaxMessagesPerPoll=false |
| Files larger than a few MB | split(body().tokenize("\n")).streaming()convertBodyTo(String.class) |
| Several Camel instances on one directory | readLock=idempotent |
Most production problems with file routes come from four defaults shown on this page: processed files go to .camel