Copying Files using Camel
This post continues on from Copying Files Using Java
Edit FileCopier.java
Edit the file FileCopier.java to add a new copyFile method, giving the following code
[code language=”java”]
package com.skills421.examples.camel.basics;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class FileCopier
{
public void copyFile(File source, File dest) throws IOException
{
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[(int) source.length()];
FileInputStream in = new FileInputStream(source);
in.read(buffer);
try
{
out.write(buffer);
}
finally
{
out.close();
in.close();
}
}
public void copyFile(final String inputPath, final String outputPath) throws Exception
{
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder()
{
public void configure()
{
from("file:"+inputPath+"?noop=true").to("file:"+outputPath);
}
});
context.start();
Thread.sleep(10000);
context.stop();
}
}
[/code]
FileCopier.java
Edit FileCopierTest.java
Edit the FileCopierTest.java code to add a second Test Case as follows:
[code language=”java”]
package com.skills421.examples.camel.basics;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
public class FileCopierTest
{
@Test
public void testCopyDirectory()
{
File inboxDir = new File("/Users/johndunning/Desktop/Camel/CamelIn");
File outboxDir = new File("/Users/johndunning/Desktop/Camel/CamelOut");
FileCopier fileCopier = new FileCopier();
try
{
outboxDir.mkdir();
File[] files = inboxDir.listFiles();
for (File source : files)
{
if (source.isFile())
{
File dest = new File(outboxDir.getPath() + File.separator + source.getName());
fileCopier.copyFile(source, dest);
}
}
}
catch (IOException e)
{
fail(e.getMessage());
}
}
@Test
public void testCopyDirectoryUsingCamel()
{
String inputPath = "/Users/johndunning/Desktop/Camel/CamelIn";
String outputPath = "/Users/johndunning/Desktop/Camel/CamelOut";
FileCopier fileCopier = new FileCopier();
try
{
fileCopier.copyFile(inputPath, outputPath);
}
catch (Exception e)
{
fail(e.getMessage());
}
}
}
[/code]
FileCopierTest.java
Remember to change your inputPath and outputPath to match your own filesystem.
Run the Test Case
You can turn off the first test by adding the annotation @Ignore (this is a really bad practise, but we will ignore that for now)
You should see that your files have once again been copied successfully.