Friday 11 January 2013

File Reading


Lets see how to read a file with multiple rows using CAMEL.

Create a java project in eclipse.
Create a folder by name testFileFolder and place the below given file.
The file that we are going to read, lets say demo.txt

Data in file, "This is my test data".

Next create a java file by name PrintData.java as given below,

package com.techexample.processor;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class PrintData implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
String data=(String)exchange.getIn().getBody();
System.out.println(data);
System.out.println("=============================");
}
}



Now the main part, we are going to create the camel context file.
Create a file with name camelContext.xml and place it inside a folder say Resource

The file context is,

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
         http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/spring 
         http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="printdata" class="com.techexample.processor.PrintData" />
<camel:camelContext id="readfile" trace="true">
<camel:route id="CsvSplit" trace="true">
<camel:from uri="file:testFileFolder?noop=true;" />
<camel:split>
<camel:tokenize token="\n" />
<camel:to uri="bean:printdata" />
</camel:split>
</camel:route>
</camel:camelContext>
</beans>


Now, we have to write a java file to bring up the camel context file.

Click this link for the java file, MyClient.java


Steps to run the camel project

Go to project properties, under java buildpath -> source , add the resource and testfileFolder.
Now right click in our MyClient.java file and click runAs -> java application


OUTPUT:

This is line one

=============================
This is line two

=============================
This is line three

=============================
This is line four

=============================
This is line five

=============================
This is line six
=============================

No comments:

Post a Comment