Month: January 2017

Reading/Writing Files using FileChannel

Posted on


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 package to get this job done but we were unable to copy the file in a Network location, there were performance issues.

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.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.
                    // its flip the buffer and set the position to zero for next write operation.
                     * Writes a sequence of bytes to this channel from the given 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 {
                    } catch (IOException e) {

Developing a RESTful Web Service Using Spring Boot 1.4

Posted on





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.


  • 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.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""

    <description>Demo project for Spring Boot</description>

        <relativePath/> <!-- lookup parent from repository -->





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

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.
public class DevOpsController {

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

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

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

    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<>();
        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.
@ComponentScan(basePackages = "com.spring.example.controller")
public class SpringBootApplication {
    public static void main(String[] args) {, args);


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