Create a new Groovy project using maven

Posted on Updated on

This is a first exercise of writing a groovy program in IntelliJ IDE. See the first post of What is Groovy here?

Below is the complete example of Groovy using maven setup.

  • Create a folder as Project name i.e GroovyExample in your project folder.
  • Create an XML ( pom.xml )file under GroovyExample folder and named it as pom.xml.
  • Copy and paste the content of pom.xml as given inline below.
  • Open IntelliJ IDE and Click on File-> Open and select pom.xml file under GroovyExample folder by navigating it through.
  •  While importing all dependencies in given pom.xml into your project then you can start writing Groovy program.
  • Right click on Project and Create a directory i.e /src/main/groovy under which all groovy file will be placed.
  • Next, Select /groovy folder and right-click to create a new Groovy file.
  • Give proper groovy file name and click OK.
  • A Groovy file will be open then continue with Groovy code as given.

Maven POM.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>GroovyExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <!--http://start.spring.io/-->
    <name>GroovyExample</name>
    <description>Demo project for Groovy Example</description>


    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerId>groovy-eclipse-compiler</compilerId>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-eclipse-compiler</artifactId>
                        <version>2.7.0-01</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.eclipse.jdt.groovy.core.groovyNature</projectnature>
                    </additionalProjectnatures>
                    <sourceIncludes>
                        <sourceInclude>**/*.groovy</sourceInclude>
                    </sourceIncludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Groovy file here :-

groovy-first-example

Advertisements

What is Groovy?

Posted on Updated on

 

What is Groovy?

Groovy is an optionally Typed, Dynamically language that runs on JVM. It is tightly integrated with the Java Language and its feature is enabled as rich and  Java friendly.

Groovy supports standard Java constructs including annotations, generics, static imports, enums, varargs and lambda expression.

Groovy source code is compiled into Java byte-code by the Groovy compiler. To run Groovy code in a Java virtual machine, only the Groovy JAR file must be present in the classpath at runtime.

A Groovy source files ends with the .groovy extension. This file can contain a Groovy script or a Groovy class.

Compatibility with Java

Groovy runs on the JVM and can use Java libraries. Every Groovy type is a subclass ofjava.lang.Object.

Groovy does currently not support Java 8 lambda expressions.

Reasons to use Groovy

Groovy focus on simplicity and very productive.

  • Simplification : – Groovy does not require a semicolon to terminate the line. return type can be omitted, by default Groovy return the last expression of the line as return type. public keyword can be omitted, it is a Default in Groovy, Also it allows optional typing.
  • Ease of use – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.
  • Flexibility – Groovy allows to change classes and methods at runtime, e.g. if a method is called which does not exist on a class, the class can intercept this call and react to it. This allows for example that Groovy provides a very flexible builder pattern.
  • Easy to use : – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.

Setup Groovy in IntelliJ:-

Steps to follow to install Groovy in you IntelliJ.

  • Open IntellJ IDE.
  • Go to File->Settings -> plugin
  •  Choose Groovy in plugin Text box and install.
  • Once Groovy get installed in your IDE, then you will able to create a Groovy file and run it.
  • groovy-setup

 

Exercise :-

 

Reading/Writing Files using FileChannel

Posted on

6db3a-download

There are multiple ways to reading/writing a file in Java. Usually, we used java.lang.IO package to read/write a file but as my last experience with copying a large file size (>256 MB ) into some other file location or on a network.

 

As we also tried to used java.lang.io package to get this job done but we were unable to copy the file in a Network location, there were performance issues.

http://stackoverflow.com/questions/1605332/java-nio-filechannel-versus-fileoutputstream-performance-usefulness

And finally, I got an alternative way to copy a file into a Network location  i.e FileChannel . its provide a better performance than InputStream/OutputStream.

Some interesting points about java.nio or FileChannel:-

  1. it’s a buffer-oriented, means- same Buffer is used to reading / writing so you can move back or forth in the Buffer as you need to.  usee flip() method to get the pointer to next position.
  2. It’s a non-blocking, i.e means a Thread request to reading data from Channel then only get what is currently available in a buffer, if data is not available then rather than blocking until data get available in buffer, Thread goes on and do something else in meantime. The same is true for non-blocking writing. A thread can request that some data be written to a channel, but not wait for it to be fully written. The thread can then go on and do something else in the mean time.
  3. Concurrent processing can be done in FileChannel which is safe for use.
  4. Channels can be read and written asynchronously.

Below example demonstrated how to write into a file using FileChannel.


 import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.IOException;
        import java.io.RandomAccessFile;
        import java.nio.ByteBuffer;
        import java.nio.channels.FileChannel;
        import java.nio.channels.WritableByteChannel;
        
        /**
         * Created by kumajye on 10/01/2017.
         */
        public class FileChannelTest {
            // This is a Filer location where write operation to be done.
            private static final String FILER_LOCATION = "C:\\documents\\test";
            // This is a text message that to be written in filer location file.
            private static final String MESSAGE_WRITE_ON_FILER = "Operation has been committed.";
        
            public static void main(String[] args) throws FileNotFoundException {
                // Initialized the File and File Channel
                RandomAccessFile randomAccessFileOutputFile = null;
                FileChannel outputFileChannel = null;
                try {
                    // Create a random access file with 'rw' permission..
                    randomAccessFileOutputFile = new RandomAccessFile(FILER_LOCATION + File.separator + "readme.txt", "rw");
                    outputFileChannel = randomAccessFileOutputFile.getChannel();
                    //Read line of code one by one and converted it into byte array to write into FileChannel.
                    final byte[] bytes = (MESSAGE_WRITE_ON_FILER + System.lineSeparator()).getBytes();
                    // Defined a new buffer capacity.
                    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
                    // Put byte array into butter array.
                    buffer.put(bytes);
                    // its flip the buffer and set the position to zero for next write operation.
                    buffer.flip();
                    /**
                     * Writes a sequence of bytes to this channel from the given buffer.
                     */
                    outputFileChannel.write(buffer);
                    System.out.println("File Write Operation is done!!");
        
                } catch (IOException ex) {
                    System.out.println("Oops Unable to proceed file write Operation due to ->" + ex.getMessage());
                } finally {
                    try {
                        outputFileChannel.close();
                        randomAccessFileOutputFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
        
                }
        
            }
        
        }


Developing a RESTful Web Service Using Spring Boot 1.4

Posted on

spring_mvc_rest

 

 

 

In this article, we will see the full example of developing an application using Spring boot 1.4.3 Release version. Along with MVC RESTFul example to accomplish a CURD operation.

Before we kick off in example details, we would give you some insight about Spring.boot

What is Spring Boot ?

It is a framework for developing a stand-alone application, Its provide defaults for code and annotation configuration that help us to quickly start new Spring project.

Spring Boot is nothing but a top up on existing Spring Framework with embedded Server ( Jetty + Tomcat ). The goal of Spring Boot Framework is to minimize the development and Testing ( JUnit & Integration ) time and provide production ready features like a metrics, health, logs and externalized configuration.

Features

  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated ‘starter’ POMs to simplify your Maven configuration
  • Automatically configure Spring whenever possible
  • Provide production-ready features such as metrics, health checks and externalized configuration
  • Absolutely no code generation and no requirement for XML configuration.

Advantages of Spring Boot:

  • It is very easy to develop Spring Based applications with Java or Groovy.
  • It reduces lots of development time and increases productivity.
  • It avoids writing lots of boilerplate Code, Annotations and XML Configuration.
  • It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
  • It follows “Opinionated Defaults Configuration” Approach to reduce Developer effort
  • It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
  • It provides CLI (Command Line Interface) tool to develop and test Spring Boot(Java or Groovy) Applications from command prompt very easily and quickly.
  • It provides lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and Gradle
  • It provides lots of plugins to work with embedded and in-memory Databases very easily.

Let start with Spring Boot Example Step by Step :-

It’s is recommended to start spring.boot application using dependency management system like Maven or Gradle. Here we use Maven to build a Spring Boot application. Below are dependencies in pom.xml which can be created manually or created by SPRING INITIALIZR – recommended to use it to develop a simple Spring Boot Application.

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.boot.example</groupId>
    <artifactId>Spring_Boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <!--http://start.spring.io/-->
    <name>spring_boot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Create a RESTFul Controller that handle CURD operation using endpoints. Spring 4.3 introduced new annotations which serve the same purpose as @RequestMapping having predefined ‘method’ (HTTP verb) value. These annotations are actually themselves annotated with @RequestMapping with the related value of ‘method’ element.

Followings are those annotations:

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

DevOpsController.java

package com.spring.example.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by MYPC on 1/9/2017.
 */
@RestController
public class DevOpsController {

    @GetMapping
    public ResponseEntity<?> sayHello() {
        return ResponseEntity.status(HttpStatus.OK).body("Welcome to my first Sprint boot example");
    }

    @PutMapping
    public ResponseEntity<?> putMethod(@RequestBody String payload) {
        System.out.println(" Put Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @PostMapping
    public ResponseEntity<?> postMethod(@RequestBody String payload) {
        System.out.println(" POST Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @DeleteMapping
    public ResponseEntity<?> deleteMethod(@RequestBody String payload) {
        System.out.println(" DELETE Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @GetMapping(path = "/list")
    public ResponseEntity<?> getList() {
        List list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
        list.add("Four");
        return ResponseEntity.status(HttpStatus.OK).body(list);
    }
}

And Main Application class to start Spring-Boot application along with Server.


package com.spring.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

/**
 * list
 * Created by AJAY KUMAR on 1/9/2017.
 */
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.spring.example.controller")
public class SpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class, args);
    }
}


 

Run SpringBootApplication.java as normal java program, It will start embedded Tomcat on port no 8080. Below are output’s snapshot.
springboot-rest

How to Schedule Future Task Using java.util.Timer

Posted on Updated on

java.util.Timer

6db3a-downloadA java.util.Timer class provides a facility to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. Timer class uses java.util.TaskQueue to add tasks at given regular interval and at any time there can be only one thread running the TimerTask.

TimerTask :-

java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

Key points :-

  • java.util.Timer is a thread safe – means, multiple threads can share a single Timer object without the need for external synchronization.
  • This class schedules tasks for one-time execution, or for repeated execution at regular intervals.
  • All constructors start a timer thread.
  • This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method.

Class Constructors :-

  • Timer() – Create a new Timer
  • Timer(boolean isDaemon) – Creates a new timer whose associated thread may be specified to run as a daemon.
  • Timer(String name) – Creates a new timer whose associated thread has the specified name.
  • Timer(String name, boolean isDaemon) – Creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon.

Class Methods :-

  • cancel() – Terminates this timer, discarding any currently scheduled tasks.
  • purge() – Removes all cancelled tasks from this timer’s task queue.
  • schedule(TimerTask task,Date time) –  Schedules the specified task for execution at the specified time.
  • schedule(TimerTask task,Date firstTime,long period) – Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.
  • schedule(TimerTask task,long delay) – Schedules the specified task for execution after the specified delay.
  • schedule(TimerTask task,long delay,long period) – Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
  • scheduleAtFixedRate(TimerTask task, Date firstTime, long period) – Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
  • scheduleAtFixedRate(TimerTask task, long delay, long period) – Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.

Example :-

Here, we scheduled a non-repeated future task that will be print on a Console after the delay of 10 min. TimerTask is a task that can be scheduled for one-time or repeated execution by a Timer and it is a sub-class of Runnable Interface.


import java.util.Timer;
import java.util.TimerTask;
/**
 * Created by MYPC on 10/8/2016.
 */
public class FutureExecutionExample {
    public static void main(String[] args) {
        Timer t = new Timer();
        t.schedule(new TimerTask() {
                  @Override
                  public void run() {
                  // Execute given scheduled task after 10 min.
                  System.out.println(" Run specific task at given time." + System.currentTimeMillis());
               }
             }
         , 10 * 60 * 1000);  // 10 mins
    }
}


Let assume, we create a Timer to run every 2 seconds interval but the execution of Thread takes 3 seconds then Timer keeping adding a schedule task in queue and as soon as Thread execution get finished then, it’s notify to queue to execute next one.


Timer t = new Timer();
t.schedule(new TimerTask() {
       @Override
       public void run() {
           System.out.println(" Run specific task at given time." + System.currentTimeMillis());
           try {
               Thread.sleep(3000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   }

, 1000,2000);  // After 1 second given task will be executed and every 2 second given task execution repeat.
}


Java 8 – Consumer Example

Posted on Updated on

Java 8 – Consumer Example 

Consumjava-8-lambdaer<T> introduced in Java 8.  Although it is a Functional Interface that  accepts only one argument and  operation to be performed on that argument but do not return anything.

Since It has only one method i.e

accept( T t);  //Performs this operation on the given argument.

and another method which is a default method– As you know that since Java 8, An Interface can be  a default method implementation which is denoted as default keyword.

default Consumer<T> andThen(Consumer<? super T> after)

Basically, this default method performs a sequence of composed consumers operation that followed by the after operation.

Below is some example that’s build up you understanding of Consumer<T> concept :-

 


package com.example1;

import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by MYPC on 9/19/2016.
 */
public class ConsumerTest {

    public static void main(String[] args) {

        /**
         * Example 1
         */
        List integerList = Stream.of(new Integer(1), new Integer(10), new Integer(200), new Integer(101), new Integer(-10), new Integer(0))
                .collect(Collectors.toList());
        forEach(integerList, (number) -> {
            System.out.println(" Number is " + number);
        });

        /**
         * Example 2
         */
        Consumer consumer = (number) -> {
            number += number;
            System.out.println(number);
        };

        /**
         * Example 3
         */
        consumer.accept(2000);
        getConsumer().accept(1000);

        /**
         * Example 4
         */
        integerList.forEach((num -> {
            System.out.println("Java 8 forEach Loop" + num);
        }));


    }

    /**
     * Return consumer that to be applied on accept(T t) parameter.
     *
     * @return
     */
    public static Consumer getConsumer() {
        return (number) -> System.out.println("Method Invoked here " + number);
    }

    /**
     * Iterate over the Collection and to be consumed by console or other system.
     *
     * @param collections
     * @param consumer
     * @param 
     */
    public static  void forEach(Collection collections, Consumer consumer) {
        collections.forEach(consumer);
    }
}


Let’s move to some other example:-

In the example, we have tried to create a generic forEach loop that’s iterating over the generated Query result and consume by some other object.

ExecutorContext.Java – Object consume data producted by getQuery().


import java.util.List;
import java.util.function.Consumer;

interface ExecutorContext {
    List getQuery();
    Consumer getConsumer();
}


StubsUtils.Java : – Utility class


class StubsUtils {

    public static void forEach(ExecutorContext executorContext) {
        executorContext.getQuery().forEach(executorContext.getConsumer());
    }
}
 

Java8ConsumerExample.Java :- This is  a Consumer client that invoked forEach loop and override  ExecutorConext interface to produce & consume the query set elements.

Here, getQuery() method returns a Collection  but it could be any Result set query that will be produced a result set by JdbcTemplate. Other method  getConsumer() will be applied the desired operation over the each element of Collection returned by getQuery() method means printing on consoles and adding into a list.

Inside the getConsumer(), you can probably apply your logic to perform the operation over the Input argument.


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8ConsumerExample {

    private static List QUERY_RESULTSET_INTEGER = Arrays.asList(new Integer(1), new Integer(10), new Integer(200), new Integer(101), new Integer(-10), new Integer(0));
    private static List QUERY_RESULTSET_STRING = Stream.of("A", "B", "C", "D", "E", "F").collect(Collectors.toList());

    public static void main(String[] args) {

        // EXAMPLE : 1

        /**
         * Iterator over the Query generated integer list and print on console.
         */
        StubsUtils.forEach(new ExecutorContext() {
            List consumerList = new ArrayList();

            /**
             * Let's assume that our query returns set of Integer that would be consume by some caller class or print on console.
             * @return
             */
            @Override
            public List getQuery() {
                return QUERY_RESULTSET_INTEGER;
            }

            @Override
            public Consumer getConsumer() {
                return x -> {
                    System.out.println(x);
                    consumerList.add(x);
                };
            }
        });

        // EXAMPLE : 2
        /**
         * Iterator over the Query generated String list and print on console.
         */
        StubsUtils.forEach(new ExecutorContext() {
            List consumerList = new ArrayList();

            /**
             * Let's assume that our query returns set of Integer that would be consume by some caller class or print on console.
             * @return
             */
            @Override
            public List getQuery() {
                return QUERY_RESULTSET_STRING;
            }

            @Override
            public Consumer getConsumer() {
                return x -> {
                    System.out.println(x);
                    consumerList.add(x);
                };
            }
        });

    }
}


Output:-

1 10 200 101 -10 0
A B C D E F

How to read/write CSV file to Map in java

Posted on Updated on

As you see in last article, how to read a CSV file into Java object with the help of Jackson API. In this article, we will see how to write a list of Map ( List<Map<String,String>> ) into a CSV file in your machine and again read it through with Jackson API.

Add this dependency in your pom.xml file to used Jackson API in your application.

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-csv</artifactId>
  <version>2.7.0</version>
</dependency>

 

Below are a sample example of reading or writing a CSV file with the help of Jackson API, which makes it very easy to write or read the CSV file into Java Object.

 


package com.example;

import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.*;
import java.util.*;

/**
 * Created by MYPC on 8/1/2016.
 */
public class ConvertMapToCSVTest {
    public static void main(String[] args) throws IOException {

        List<HashMap<String, String>> myArrList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        /*** Rows 1 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C001");
        map.put("Name", "Ajay Kumar");
        map.put("Email", "ajay@gmail.com");
        map.put("CountryCode", "TH");
        map.put("Budget", "1000000");
        map.put("Used", "600000");
        myArrList.add(map);

        /*** Rows 2 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C002");
        map.put("Name", "Rahul Kumar");
        map.put("Email", "Rahul.kumar@gmail.com");
        map.put("CountryCode", "UK");
        map.put("Budget", "2000000");
        map.put("Used", "800000");
        myArrList.add(map);

        /*** Rows 3 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C003");
        map.put("Name", "Wasim Akram");
        map.put("Email", "waism.atnet@rediff.com");
        map.put("CountryCode", "US");
        map.put("Budget", "3000000");
        map.put("Used", "600000");
        myArrList.add(map);

        /*** Rows 4 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C004");
        map.put("Name", "Santosh Kumar");
        map.put("Email", "santosh.ku@yahoo.com");
        map.put("CountryCode", "US");
        map.put("Budget", "4000000");
        map.put("Used", "100000");
        myArrList.add(map);

        File file = new File("d:\\sample.csv");
        // Create a File and append if it already exists.
        Writer writer = new FileWriter(file, true);
        Reader reader = new FileReader(file);
        //Copy List of Map Object into CSV format at specified File location.
        csvWriter(myArrList, writer);
        //Read CSV format from specified File location and print on console..
        csvReader(reader);
    }

    /**
     * @param listOfMap
     * @param writer
     * @throws IOException
     */
    public static void csvWriter(List<HashMap<String, String>> listOfMap, Writer writer) throws IOException {
        CsvSchema schema = null;
        CsvSchema.Builder schemaBuilder = CsvSchema.builder();
        if (listOfMap != null && !listOfMap.isEmpty()) {
            for (String col : listOfMap.get(0).keySet()) {
                schemaBuilder.addColumn(col);
            }
            schema = schemaBuilder.build().withLineSeparator("\r").withHeader();
        }
        CsvMapper mapper = new CsvMapper();
        mapper.writer(schema).writeValues(writer).writeAll(listOfMap);
        writer.flush();
    }

    /**
     * 
     * @param collection
     * @param writer
     * @param 
     * @throws IOException
     */
    public static  void csvWriter(Collection collection, Writer writer) throws IOException {
        if (collection != null && collection.size() > 0) {
            CsvMapper mapper = new CsvMapper();
            Object[] objects = collection.toArray();
            Class type = objects[0].getClass();
            CsvSchema schema = mapper.schemaFor(type).withHeader();
            mapper.writer(schema).writeValues(writer).write(objects);
        } else {
            writer.write("No Data");
        }
        writer.flush();
    }


    /**
     * @param reader
     * @throws IOException
     */

    public static void csvReader(Reader reader) throws IOException {
        Iterator<Map<String, String>> iterator = new CsvMapper()
                .readerFor(Map.class)
                .with(CsvSchema.emptySchema().withHeader())
                .readValues(reader);
        while (iterator.hasNext()) {
            Map<String, String> keyVals = iterator.next();
            System.out.println(keyVals);
        }
    }
}


A CSV file is created at specified location i.e d:\\sample.csv in file system.

Email,Used,Budget,CustomerID,CountryCode,Name
ajay@gmail.com,600000,1000000,C001,TH,"Ajay Kumar"
Rahul.kumar@gmail.com,800000,2000000,C002,UK,"Rahul Kumar"
waism.atnet@rediff.com,600000,3000000,C003,US,"Wasim Akram"
santosh.ku@yahoo.com,100000,4000000,C004,US,"Santosh Kumar"

Reading sample.csv file from file system.

{Email=ajay@gmail.com, Used=600000, Budget=1000000, CustomerID=C001, CountryCode=TH, Name=Ajay Kumar}
{Email=Rahul.kumar@gmail.com, Used=800000, Budget=2000000, CustomerID=C002, CountryCode=UK, Name=Rahul Kumar}
{Email=waism.atnet@rediff.com, Used=600000, Budget=3000000, CustomerID=C003, CountryCode=US, Name=Wasim Akram}
{Email=santosh.ku@yahoo.com, Used=100000, Budget=4000000, CustomerID=C004, CountryCode=US, Name=Santosh Kumar}

Hoping, It would be helpful !! Thanks