This post is in continuation with web service tutorial (Part -10).
    Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS json example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Restful web services simple example Spring Restful web services json example Spring Restful web services CRUD example
In previous post, we have used @QueryParam for passing parameter to URL in JAX-RS @QueryParam example and  In case of @QueryParam, we pass parameters as well as its values separated by ? but in case of @MatrixParam, key value pairs are separared by semicolon(;). 

For example:
http://localhost:8080/JAXRSJsonExample/rest/countries/country;id=1;countryName=India
Here Parameter names are id,countryName and its values are 3,Nepal respectively separated by ;.

Here are steps to create a JAXRS json example which will use @MatrixParam.

1) Follow steps on RESTful Web Services json example to create simple RESTful web services which uses @PathParam.
2) Change CountryRestService.java to use @MatrixParam as below.

package org.arpit.java2blog.jaxrs;

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

import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.arpit.java2blog.bean.Country;
/* 
 * author: Arpit Mandliya
 * */
@Path("/countries")
public class CountryRestService {
 
    @GET
    @Produces(MediaType.APPLICATION_JSON)
 public List<Country> getCountries()
 {
  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries=createCountryList();
  return listOfCountries;
 }

 @GET
    @Path("/country")
    @Produces(MediaType.APPLICATION_JSON)
 public Country getCountryById(@MatrixParam("id") int id,@MatrixParam("countryName") String countryName)
 {
  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries=createCountryList();

  for (Country country: listOfCountries) {
   if(country.getId()==id && country.getCountryName().equalsIgnoreCase(countryName))
    return country;
  }
  
  return null;
 }

// Utiliy method to create country list.
 public List<Country> createCountryList()
 {
  Country indiaCountry=new Country(1, "India");
  Country chinaCountry=new Country(4, "China");
  Country nepalCountry=new Country(3, "Nepal");
  Country bhutanCountry=new Country(2, "Bhutan");

  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries.add(indiaCountry);
  listOfCountries.add(chinaCountry);
  listOfCountries.add(nepalCountry);
  listOfCountries.add(bhutanCountry);
  return listOfCountries;
 }
}

That's all. We need to run the application now.

Run the application

3) Right click on project -> run as -> run on server
Select apache tomcat and click on finish



4) Now pass country id and country name as parameters to url separated by ;.
"http://localhost:8080/JAXRSJsonExample/rest/countries/country;id=1;countryName=India".


We are done with Restful web services json MatrixParam example. If you are still facing any issue, please comment.

In this post, we will see Spring MVC file upload example. We have already seen struts 2 file upload example.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example
Spring MVC uses Apache common FileUpload API to upload file. It is very easy to configure file upload in Spring MVC.

Project structure for below example:


Steps for Spring MVC file upload example:

1) Create dynamic web project using maven named "SpringMVCFileUploadExample".

2) Maven dependencies

It requires spring dependency as we have put in spring mvc hello world example. It requires apache common io jars too, so we need to put following dependency for it.
 <!-- Apache Common io dependencies -->
  <!-- Apache Commons FileUpload -->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
  </dependency>

  <!-- Apache Commons IO -->
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>
So pom.xml will be as below
<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/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>org.arpit.java2blog</groupId>
 <artifactId>SpringMVCFileUploadExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringMVCFileUploadExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>
  <!-- Spring dependency -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>

  <!-- Apache Common io dependencies -->
  <!-- Apache Commons FileUpload -->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
  </dependency>

  <!-- Apache Commons IO -->
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>SpringMVCFileUploadExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>

</project>

3) Create model,controller and validator

Create a class model called "FileUpload.java" in packge org.arpit.java2blog.model and it will have variable of type MultiFilePart.
package org.arpit.java2blog.model;
import org.springframework.web.multipart.MultipartFile;

public class FileUpload {

 MultipartFile file;

 public MultipartFile getFile() {
  return file;
 }

 public void setFile(MultipartFile file) {
  this.file = file;
 }
}

Create class FileUploadController.java in package org.arpit.java2blog.controller . It is spring controller and to understand more above controller, please go through Spring MVC hello world example.
package org.arpit.java2blog.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.arpit.java2blog.model.FileUpload;
import org.arpit.java2blog.validator.FileUploadValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

 @Autowired
 FileUploadValidator fileValidator;

 @RequestMapping("/fileUploadForm")
 public ModelAndView getUploadForm(
   @ModelAttribute("uploadedFile") FileUpload uploadedFile,
   BindingResult result) {
  return new ModelAndView("fileUploadForm");
 }


 // When click on submit, below method will get called
 @RequestMapping("/submitFileUpload")
 public ModelAndView fileUploaded(
   @ModelAttribute("uploadedFile") FileUpload uploadedFile,
   BindingResult result) {
  InputStream inputStream = null;
  OutputStream outputStream = null;

  // Getting uploaded file
  MultipartFile file = uploadedFile.getFile();
  fileValidator.validate(uploadedFile, result);

  String fileName = file.getOriginalFilename();

  // If it has error, redirect it to same page
  if (result.hasErrors()) {
   return new ModelAndView("fileUploadForm");
  }

  try {
   inputStream = file.getInputStream();

   File newFile = new File("/Users/Arpit/Documents/SpringMVCUploadedFiles/" + fileName);
   if (!newFile.exists()) {
    newFile.createNewFile();
   }
   outputStream = new FileOutputStream(newFile);
   int read = 0;
   byte[] bytes = new byte[1024];

   while ((read = inputStream.read(bytes)) != -1) {
    outputStream.write(bytes, 0, read);
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  return new ModelAndView("fileUploadSuccess", "fileName", fileName);
 }

}


We need validator for validations such as no files selected. Create validator FileUploadValidator.java in package org.arpit.java2blog.validator
package org.arpit.java2blog.validator;

import org.arpit.java2blog.model.FileUpload;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;


public class FileUploadValidator implements Validator{

 @Override
 public boolean supports(Class clazz) {
  //just validate the FileUpload instances
  return FileUpload.class.isAssignableFrom(clazz);
 }

 @Override
 public void validate(Object target, Errors errors) {
  
  FileUpload file = (FileUpload)target;
  
  if(file.getFile().getSize()==0){
   errors.rejectValue("file", "uploadForm.selectFile",  
         "Please select a file!");
  }
 }
}

4)  Spring configuration

It will have simple web.xml for spring as in hello world example.
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
     <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping> 
    </web-app>

We need to change in "springmvc-dispatcher-servlet.xml" as below
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="org.arpit.java2blog.controller" />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/JSP/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
   <!-- Validator -->
   <bean id="fileValidator" class="org.arpit.java2blog.validator.FileUploadValidator" />  
  
 <bean id="multipartResolver"  
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />  
 <mvc:annotation-driven/>

</beans>
We need to declare multipartResolver bean in above file to enable file upload. We have also put bean entry of validator.

5) Views 

Finally create views for file upload form and file upload success page. Create fileUploadForm.jsp in /WEB-INF/JSP/ folder
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<title>Spring MVC file upload</title>
</head>
<body>
 <center>
  <h2>Spring MVC file upload</h2>
  <h3>Please select a file to upload !</h3>
  
  <form:form method="post" enctype="multipart/form-data"
   modelAttribute="uploadedFile" action="submitFileUpload.htm">
   <table>
    <tr>
     <td>Upload File: </td>
     <td><input type="file" name="file" />
     </td>
     <td style="color: red; font-style: italic;"><form:errors
       path="file" />
     </td>
    </tr>
    <tr>
     <td> </td>
     <td><input type="submit" value="Upload" />
     </td>
     <td> </td>
    </tr>
   </table>
  </form:form>
 </center>
</body>
</html>


create filUploadSuccess.jsp /WEB-INF/JSP/ folder
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<body>
 <h2>Spring MVC file upload example</h2>

 FileName : "
 <strong> ${fileName} </strong>" - Uploaded Successful.

</body>
</html>

6) Its time for maven build 

   Provide goals as clean install (given below) and click on run


7) Run the application

Right click on project -> run as -> run on server
Select apache tomcat and click on finish

You will see below screen:
URL : http://localhost:8080/SpringMVCFileUploadExample/fileUploadForm.htm


 If you directly click on upload button without selecting any file, it will give you error as "Please select a file"



Lets upload "config.properties" 


If your file is successfully uploaded, you will see below screen.


You can check in the folder whose path you have given in above application.



8) Source code

click to begin
20KB .zip

Bingo!! We are done with Spring MVC file upload example.

Logging is essential part of programming. It helps developer to track code workflow and fix bugs efficiently. If we get any issue in the code, we check logs for that workflow or functionality.

Log4j is fast , reliable logging framework and can be easily integrated with the code. It is possible to enable logging at run time without using

Lets integrate Log4j in simple maven project.

Steps:

1) Create simple maven java project.

2) Put log4j entry in pom.xml .

<dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
</dependency>

3) Update maven project to download require jar

Right click on project-> Maven -> update project

4) Sample class for Logger 

Create a class called "LoggingMain.java" in src/main/java in package org.arpit.java2blog
package org.arpit.java2blog;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class LoggingMain {

  private static final Logger logger = LogManager.getLogger(LoggingMain.class);
 public static void main(String[] args) {
  // basic log4j configurator
  BasicConfigurator.configure();
  logger.info("Hello world");
  logger.info("we are in logger info mode");

 }

}

5) Run program:

When you run above program , you will get below output:
0 [main] INFO org.arpit.java2blog.LoggingMain  - Hellow world
1 [main] INFO org.arpit.java2blog.LoggingMain  - we are in logger info mode
Bingo!! we have successfully configured log4j in maven project.

In this post , we will see how to configure spring with java based configuration. In previous post, we have already seen how to configure spring using xml configuration. Spring provides @configuaration and @Bean annotation for java based configuration.

Steps for spring java based configuration:

Project structure for below project:


1. Create a simple java maven project.

2. Maven dependency

put spring and cglib maven dependency in pom.xml.
<dependencies>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
<!-- cglib required for @configuration annotation -->
   <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.0</version>
        </dependency>
 </dependencies>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
 </properties>
So your pom.xml will look like:
<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>org.arpit.java2blog</groupId>
  <artifactId>SpringHelloWorldJavaBasedConfiguration</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringHelloWorldJavaBasedConfiguration</name>
  <description>It provides hello world program for java based config
</description>

 <dependencies>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
<!-- cglib required for @configuration annotation -->
   <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.0</version>
        </dependency>
 </dependencies>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
 </properties>
</project>

3. Create Bean class

Create a bean class called country.java in package org.arpit.java2blog.model
package org.arpit.java2blog.model;

public class Country {

    String countryName;
    
    public Country(String countryName) {
  this.countryName=countryName;
 }
 public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

}

4. Create application configuration class

This class will have @Configuaration and @Bean annotation .

Create class called ApplicationConfiguration.java in package org.arpit.java2blog.config
package org.arpit.java2blog.config;
import org.arpit.java2blog.model.Country;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfiguration {

 @Bean(name="countryObj")
 public Country getCountry()
 {
  return new Country("India");
 }
 
}

Above file is equivalent to below spring configuration xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
<context:annotation-config/>  
 <bean id="countryObj" class="org.arpit.java2blog.Country" >
  <property name="countryName" value="India"/>
 </bean>
</beans>

5. Create main class to run the program

Create class called SpringJavaConfigMain.java
package org.arpit.java2blog.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.arpit.java2blog.config.ApplicationConfiguration;
import org.arpit.java2blog.model.Country;;

public class SpringJavaConfigMain {

 public static void main(String[] args) {
  @SuppressWarnings("resource")
  ApplicationContext appContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
  Country countryObj = (Country) appContext.getBean("countryObj");
  String countryName=countryObj.getCountryName();
  
  System.out.println("Country name: "+ countryName);
 }
}

6. Run above program 

When you run above program, you will get below output.
Feb 19, 2016 4:09:08 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2096ed8b: startup date [Fri Feb 19 16:09:08 IST 2016]; root of context hierarchy
Country name: India

7. Source code 

click to begin
20KB .zip

Bingo!! we are done with spring java based configuaration.

Spring autowiring byName means autowiring on the basis of name. If any bean property matches with exact one other bean's name declaration then spring will automatically takes care of dependency. 

Below diagram will make it clear:


For example:
I am taking example of autowire "byName" here.It will be almost same as Dependency injection via setter method with some changes in XML configuration file.

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.java2blog.Copy following content into Country.java.
package org.arpit.java2blog;

public class Country {

    String countryName;
   
    Capital capitalObj;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
 public Capital getCapitalObj() {
  return capitalObj;
 }
 public void setCapitalObj(Capital capitalObj) {
  this.capitalObj = capitalObj;
 }
   
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.java2blog.java.Above Country class contains object of this class.Copy following content into Capital.java
package org.arpit.java2blog;

public class Capital {

       String capitalName;

       public String getCapitalName() {
              return capitalName;
       }

       public void setCapitalName(String capitalName) {
              this.capitalName = capitalName;
       }
}

3.BeanAutowiringByTypeMain.java

This class contains main function.Create BeanAutowiringByNameMain.java under package org.arpit.java2blog.Copy following content into BeanAutowiringByNameMain.java

package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanAutowiringByNameMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        Country countryObj = (Country) appContext.getBean("country");
        String countryName=countryObj.getCountryName();
        String capitalName=countryObj.getCapitalObj().getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
       
    }
}

You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans.

4.ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.java2blog.Country" autowire="byName">
  <property name="countryName" value="India"/>
 </bean>
 <bean id="capital" class="org.arpit.java2blog.Capital">
  <property name="capitalName" value="Delhi" />
 </bean>
</beans>

Here in <bean>,we have used autowire attribute and set it to "byName".So now spring container will match "capitalObj" reference in Country class with id or name of other beans in XML configuration file. So here you can see we have bean with id as "capitalObj"

5.Run it

When you will run above application,you will get following as output.
Delhi is capital of India

Java Apache POI tutorial:

    Read excel files in java using POI Write excel files in java using POI Working with formula in excel using POI How to set style in excel using POI
In this post, we will see how to set and evaluate formulas in excel using Apache POI.

Set formula for a cell:

For setting a formula for cell, you need to use following code:
 // Setting cell formula and cell type
 Cell cell = row.createCell(2);
 cell.setCellFormula("SUM(C2:C5)");
 cell.setCellType(Cell.CELL_TYPE_FORMULA);
We will use same code which we have used to write CountriesDetails.xlsx in previous post and add row for total population and evaluate it using formula.

Java program:

package org.arpit.java2blog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WriteExcelMain {

 public static void main(String[] args) throws IOException {
  writeFileUsingPOI();
 }

 public static void writeFileUsingPOI() throws IOException 
 {
  //create blank workbook
  XSSFWorkbook workbook = new XSSFWorkbook(); 

  //Create a blank sheet
  XSSFSheet sheet = workbook.createSheet("Country");

  ArrayList<Object[]> data=new ArrayList<Object[]>();
  data.add(new String[]{"Country","Capital","Population"});
  data.add(new Object[]{"India","Delhi",10000});
  data.add(new Object[]{"France","Paris",40000});
  data.add(new Object[]{"Germany","Berlin",20000});
  data.add(new Object[]{"England","London",30000});


  //Iterate over data and write to sheet
  int rownum = 0;
  for (Object[] countries : data)
  {
   Row row = sheet.createRow(rownum++);

   int cellnum = 0;
   for (Object obj : countries)
   {
    Cell cell = row.createCell(cellnum++);
    if(obj instanceof String)
     cell.setCellValue((String)obj);
    else if(obj instanceof Double)
     cell.setCellValue((Double)obj);
    else if(obj instanceof Integer)
     cell.setCellValue((Integer)obj);
   }
  }
  Row rowGap = sheet.createRow(rownum++);
  Row row = sheet.createRow(rownum++);
  Cell cellTotal = row.createCell(0);
  cellTotal.setCellValue("Total Population");
  
  // Setting cell formula and cell type
  Cell cell = row.createCell(2);
  cell.setCellFormula("SUM(C2:C5)");
  cell.setCellType(Cell.CELL_TYPE_FORMULA);
  try
  {
   //Write the workbook to the file system
   FileOutputStream out = new FileOutputStream(new File("CountriesDetails.xlsx"));
   workbook.write(out);
   out.close();
   System.out.println("CountriesDetails.xlsx has been created successfully");
  } 
  catch (Exception e) 
  {
   e.printStackTrace();
  }
  finally {
   workbook.close();
  }
 }


}

When you run above program, you will get following output:
CountriesDetails.xlsx has been created successfully

Lets see content of CountriesDetails.xlsx now.

We have calculated total population using sum(c2:c5) in c7.

Formula evaluators:

When you update any cell which has impact on formula, you need to reevaluate the cell.
Apache poi API has provided FormulaEvalutor class to evaluate formula.

It has four method to evaluate formula:
1) public void evaluateAll()
It evaluates all cell which presents in workbook and it recalculates all formula and save the result and formula cells remains formula cells too. If cell do not have formula, it remains the same.

2) CellValue evaluate()
It evaluates formula cell and returns its cell value, it does not change original content of cell.

3) int evaluateFormulaCell(Cell cell)
It evaluates formula cell and returns its cell type. It saves calculated value. Cell remains as formula cell.

4) Cell evaluateInCell(Cell cell)
It evaluates formulas and return Cell object . It updates formula cell with latest value and cell will no longer formula cell.

Example for evaluate method:

 package org.arpit.java2blog;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadWriteExcelMain {

 public static void main(String[] args) throws IOException {
  readFileUsingPOI();
 }

 public static void readFileUsingPOI() throws IOException 
 {
  ClassLoader classLoader = ReadWriteExcelMain.class.getClassLoader();
  String excelFilePath = "CountriesDetails.xlsx";
  FileInputStream inputStream = new FileInputStream(new File(classLoader.getResource(excelFilePath).getFile()));

  Workbook workbook = new XSSFWorkbook(inputStream);
  Sheet sheet = workbook.getSheetAt(0);
  
  // Creating formula evaluator object
  FormulaEvaluator formulaEval = workbook.getCreationHelper().createFormulaEvaluator();
  
  Iterator<Row> iterator = sheet.iterator();

  while (iterator.hasNext()) {
   Row nextRow = iterator.next();
   Iterator<Cell> cellIterator = nextRow.cellIterator();

   while (cellIterator.hasNext()) {
    Cell cell = cellIterator.next();

    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
     System.out.print(cell.getStringCellValue());
     break;
    case Cell.CELL_TYPE_NUMERIC:
     System.out.print(cell.getNumericCellValue());
     break;
    case Cell.CELL_TYPE_BOOLEAN:
     System.out.print(cell.getBooleanCellValue());
     break;
    case Cell.CELL_TYPE_FORMULA:
    {
     // Evaluting cell
      CellValue c=formulaEval.evaluate(cell);
     System.out.println(c.getNumberValue());
    }
    }
    System.out.print(" | ");
   }
   System.out.println();
  }

  workbook.close();
  inputStream.close();
 }
}

When you run above file, you will get following output:
Country | Capital | Population | 
India | Delhi | 10000.0 | 
France | Paris | 40000.0 | 
Germany | Berlin | 20000.0 | 
England | London | 30000.0 | 

Total Population | 100000.0
 | 

Java Apache POI tutorial:

    Read excel files in java using POI Write excel files in java using POI Working with formula in excel using POI How to set style in excel using POI
In this post , we will see how to set style in excel using apache poi.

You can put cell style with below code:

                           
        // create font
        XSSFFont font= workbook.createFont();
        font.setFontHeightInPoints((short)10);
        font.setFontName("Arial");
        font.setColor(IndexedColors.WHITE.getIndex());
        font.setBold(true);
        font.setItalic(false);
                                    
         // Create cell style 
        CellStyle style=workbook.createCellStyle();;
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        // Setting font to style
        style.setFont(font);
        
        // Setting cell style
        cell.setCellStyle(style);

Java Program :

package org.arpit.java2blog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WriteExcelMain {

 public static void main(String[] args) throws IOException {
  writeFileUsingPOI();
 }

 public static void writeFileUsingPOI() throws IOException 
 {
  //create blank workbook
  XSSFWorkbook workbook = new XSSFWorkbook(); 

  //Create a blank sheet
  XSSFSheet sheet = workbook.createSheet("Country");

  ArrayList<Object[]> data=new ArrayList<Object[]>();
  data.add(new String[]{"Country","Capital","Population"});
  data.add(new Object[]{"India","Delhi",10000});
  data.add(new Object[]{"France","Paris",40000});
  data.add(new Object[]{"Germany","Berlin",20000});
  data.add(new Object[]{"England","London",30000});


  //Iterate over data and write to sheet
  int rownum = 0;
  for (Object[] countries : data)
  { 
   Row row = sheet.createRow(rownum++);
   
   int cellnum = 0;
   for (Object obj : countries)
   {
    Cell cell = row.createCell(cellnum++);
    if(obj instanceof String)
     cell.setCellValue((String)obj);
    else if(obj instanceof Double)
     cell.setCellValue((Double)obj);
    else if(obj instanceof Integer)
     cell.setCellValue((Integer)obj);
    // Setting style only for header
    if(rownum==1)
    {
     CellStyle style=null;
     // Creating a font
        XSSFFont font= workbook.createFont();
        font.setFontHeightInPoints((short)10);
        font.setFontName("Arial");
        font.setColor(IndexedColors.WHITE.getIndex());
        font.setBold(true);
        font.setItalic(false);

        style=workbook.createCellStyle();;
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        // Setting font to style
        style.setFont(font);
        
        // Setting cell style
        cell.setCellStyle(style);
    }
   }
   
   
  }
  Row rowGap = sheet.createRow(rownum++);
  Row row = sheet.createRow(rownum++);
  Cell cellTotal = row.createCell(0);
  cellTotal.setCellValue("Total Population");
  
  // Setting cell formula and cell type
  Cell cell = row.createCell(2);
  cell.setCellFormula("SUM(C2:C5)");
  cell.setCellType(Cell.CELL_TYPE_FORMULA);
  try
  {
   //Write the workbook to the file system
   FileOutputStream out = new FileOutputStream(new File("CountriesDetails.xlsx"));
   workbook.write(out);
   out.close();
   System.out.println("CountriesDetails.xlsx has been created successfully");
  } 
  catch (Exception e) 
  {
   e.printStackTrace();
  }
  finally {
   workbook.close();
  }
 }
}

When you run above program, you will get following output:
CountriesDetails.xlsx has been created successfully

Lets see content of CountriesDetails.xlsx now.



In this post, we will see how to write excel in java using Apache POI example.

The Apache POI Project's mission is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft's OLE 2 Compound Document format (OLE2). In short, you can read and write MS Excel files using Java.

Java Apache POI tutorial:

    Read excel files in java using POI Write excel files in java using POI Working with formula in excel using POI How to set style in excel using POI

Some basics about Apache POI:

There are two prefixes which you encounter while reading/writing excel in java

HSSF: Used for dealing with files excel 2003 or earlier(.xls). Some of classes with HSSF prefix are HSSFWorkbook , HSSFSheet , HSSFRow and HSSFCell.

XSSF: Used for dealing with files excel 2007 or later(.xlsx). Some of classes with XSSF prefix are XSSFWorkbook , XSSFSheet , XSSFRow and XSSFCell.

Here are few classes which you need to aware of.
  • Workbook : This is high level class for representing excel workbook. 
  • Sheet : This is high level class for representing excel sheet. 
  • Row : This is high level class for representing excel row. It has methods which are related to row.
  • Cell: This is high level class for representing individual excel cell. It has methods which are related to cell for example : getDataType().

Dependency:

If you are using maven, then you need to add below dependency in pom.xml.

   org.apache.poi
   poi
   3.13
  
  
   org.apache.poi
   poi-ooxml
   3.13 

If you are not using maven, then you need to add below jars in classpath.
  • poi-3.13.jar
  • commons-codec-1.9.jar
  • poi-ooxml-3.13.jar
  • poi-ooxml-schemas-3.13.jar
  • xmlbeans-2.6.0.jar
  • stax-api-1.0.1.jar

write excel file using poi:

  1. Create a blank workbook
  2. XSSFWorkbook workbook = new XSSFWorkbook();
  3. Create a sheet and pass name of the sheet
  4. XSSFSheet sheet = workbook.createSheet("Country");
  5. Create row
  6. Row row = sheet.createRow(rownum++);
  7. Create cells, set its value and add cell to above row
  8. Cell cell = row.createCell(cellnum++); if(obj instanceof String) cell.setCellValue((String)obj); else if(obj instanceof Double) cell.setCellValue((Double)obj); else if(obj instanceof Integer) cell.setCellValue((Integer)obj);
  9. Repeat 3 and 4 until you have data

Java Program:

We are going to write excel file named  "CountriesDetails.xlsx" Create WriteExcelMain.java as below
package org.arpit.java2blog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WriteExcelMain {

 public static void main(String[] args) throws IOException {
  writeFileUsingPOI();
 }

 public static void writeFileUsingPOI() throws IOException 
 {
  //create blank workbook
  XSSFWorkbook workbook = new XSSFWorkbook(); 

  //Create a blank sheet
  XSSFSheet sheet = workbook.createSheet("Country");

  ArrayList<Object[]> data=new ArrayList<Object[]>();
  data.add(new String[]{"Country","Capital","Population"});
  data.add(new Object[]{"India","Delhi",10000});
  data.add(new Object[]{"France","Paris",40000});
  data.add(new Object[]{"Germany","Berlin",20000});
  data.add(new Object[]{"England","London",30000});


  //Iterate over data and write to sheet
  int rownum = 0;
  for (Object[] countries : data)
  {
   Row row = sheet.createRow(rownum++);

   int cellnum = 0;
   for (Object obj : countries)
   {
    Cell cell = row.createCell(cellnum++);
    if(obj instanceof String)
     cell.setCellValue((String)obj);
    else if(obj instanceof Double)
     cell.setCellValue((Double)obj);
    else if(obj instanceof Integer)
     cell.setCellValue((Integer)obj);
   }
  }
  try
  {
   //Write the workbook in file system
   FileOutputStream out = new FileOutputStream(new File("CountriesDetails.xlsx"));
   workbook.write(out);
   out.close();
   System.out.println("CountriesDetails.xlsx has been created successfully");
  } 
  catch (Exception e) 
  {
   e.printStackTrace();
  }
  finally {
   workbook.close();
  }
 }


}

When you run above program, you will get following output:
CountriesDetails.xlsx has been created successfully

Lets see content of CountriesDetails.xlsx now.




In this post, we will see how to convert existing java project to simple java maven project.

Steps for converting existing java project to maven project:

Step 1:
Install m2eclipse for maven plugin in eclipse. Please follow this link for installing m2eclipse plugin in eclipse.

Step 2:
Right click on project -> configure -> convert to maven project.

Provide group id and artifact id , I have kept them default.

Let me tell you more about group id and artifact id.

Group id : It uniquely identifies your project among all. So it may be something like com.companyname

Artifact id : It is name of jar or war without version. it may be something like project, so here we have put artifact id as ReadPropertiesFileJavaExample.



Step 3:
Click on finish button.

Step 4:
Just remember to put all dependencies in pom.xml


Bingo!! You have converted existing java project to maven project

In this post, we will see how to read excel in java using Apache POI example.

The Apache POI Project's mission is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft's OLE 2 Compound Document format (OLE2). In short, you can read and write MS Excel files using Java.

Java Apache POI tutorial:

    Read excel files in java using POI Write excel files in java using POI Working with formula in excel using POI How to set style in excel using POI

Some basics about Apache POI:

There are two prefixes which you encounter while reading/writing excel in java

HSSF: Used for dealing with files excel 2003 or earlier(.xls). Some of classes with HSSF prefix are HSSFWorkbook , HSSFSheet , HSSFRow and HSSFCell.

XSSF: Used for dealing with files excel 2007 or later(.xlsx). Some of classes with XSSF prefix are XSSFWorkbook , XSSFSheet , XSSFRow and XSSFCell.

Here are few classes which you need to aware of.
  • Workbook : This is high level class for representing excel workbook. 
  • Sheet : This is high level class for representing excel sheet. 
  • Row : This is high level class for representing excel row. It has methods which are related to row.
  • Cell: This is high level class for representing individual excel cell. It has methods which are related to cell for example : getDataType().

Dependency:

If you are using maven, then you need to add below dependency in pom.xml.

   org.apache.poi
   poi
   3.13
  
  
   org.apache.poi
   poi-ooxml
   3.13 

If you are not using maven, then you need to add below jars in classpath.
  • poi-3.13.jar
  • commons-codec-1.9.jar
  • poi-ooxml-3.13.jar
  • poi-ooxml-schemas-3.13.jar
  • xmlbeans-2.6.0.jar
  • stax-api-1.0.1.jar

Read excel file using poi:


Java Program:

We are going to read countries.xlsx. Its content is :


Create ReadWriteExcelMain.java as below
package org.arpit.java2blog;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelMain {

 public static void main(String[] args) throws IOException {
  readFileUsingPOI();
 }

 public static void readFileUsingPOI() throws IOException 
 {
  ClassLoader classLoader = ReadWriteExcelMain.class.getClassLoader();
  String excelFilePath = "Countries.xlsx";
  FileInputStream inputStream = new FileInputStream(new File(classLoader.getResource(excelFilePath).getFile()));

  Workbook workbook = new XSSFWorkbook(inputStream);
  Sheet sheet = workbook.getSheetAt(0);

  Iterator<row> iterator = sheet.iterator();

  while (iterator.hasNext()) {
   Row nextRow = iterator.next();
   Iterator<cell> cellIterator = nextRow.cellIterator();

   while (cellIterator.hasNext()) {
    Cell cell = cellIterator.next();

    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
     System.out.print(cell.getStringCellValue());
     break;
    case Cell.CELL_TYPE_NUMERIC:
     System.out.print(cell.getNumericCellValue());
     break;
    case Cell.CELL_TYPE_BOOLEAN:
     System.out.print(cell.getBooleanCellValue());
     break;
    }
    System.out.print(" | ");
   }
   System.out.println();
  }

  workbook.close();
  inputStream.close();
 }


}

When you run above program, you will get following output:
Country | Capital | Population | 
India | Delhi | 10000.0 | 
France | Paris | 40000.0 | 
Germany | Berlin | 20000.0 | 
England | London | 30000.0 | 

Lets be more object oriented. 

We will read each row and create country object. Obviously we will skip header row.
Create a class called Country.java in package com.arpit.java2blog.model
package com.arpit.java2blog.model;

public class Country {

 String name;
 String capital;
 double population;

 //getter and setter methods

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getPopulation() {
  return population;
 }

 public void setPopulation(double population) {
  this.population = population;
 }

 public String getCapital() {
  return capital;
 }

 public void setCapital(String capital) {
  this.capital = capital;
 }
 
 public String toString()
 {
  return name+" | "+capital+" | "+population ;
 }

}
ReadExcelWithCounryMain.java

package org.arpit.java2blog;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.arpit.java2blog.model.Country;
public class ReadExcelWithCountryMain {

 public static void main(String[] args) throws IOException {
  List<Country> countries=readFileUsingPOI();
  for(Country country:countries)
  {
   System.out.println(country.toString());
  }
 
 }

 public static List<Country> readFileUsingPOI() throws IOException 
 {
  List<Country> countries=new ArrayList<Country>();
  
  ClassLoader classLoader = ReadExcelWithCountryMain.class.getClassLoader();
  String excelFilePath = "Countries.xlsx";
  FileInputStream inputStream = new FileInputStream(new File(classLoader.getResource(excelFilePath).getFile()));

  Workbook workbook = new XSSFWorkbook(inputStream);
  Sheet sheet = workbook.getSheetAt(0);

  Iterator<Row> iterator = sheet.iterator();
    while (iterator.hasNext()) {
   Row nextRow = iterator.next();
   
   // Not creating country object for header
   if(nextRow.getRowNum()==0)
    continue;
   
   Country countryObj=new Country();
   Iterator<Cell> cellIterator = nextRow.cellIterator();
   
   while (cellIterator.hasNext()) {
    Cell cell = cellIterator.next();
    int columnIndex=cell.getColumnIndex();
    switch (columnIndex+1) {
    case 1:
     countryObj.setName(cell.getStringCellValue());
     break;
    case 2:
     countryObj.setCapital(cell.getStringCellValue());
     break;
    case 3:
     countryObj.setPopulation(cell.getNumericCellValue());
     break;
    }
    
   }
   countries.add(countryObj);
   
  }

  workbook.close();
  inputStream.close();
  
  return countries;
 }


}

When you run above program, you will get following output:
India | Delhi | 10000.0
France | Paris | 40000.0
Germany | Berlin | 20000.0
England | London | 30000.0




In this post, we will see how to detect OS which you are using. You can use System.getProperty("os.name") to get current OS name. Sometimes , we need to write logic based on OS, so we get use this logic to detect current OS.

Java Program:

package org.arpit.java2blog;

/*
 * @Author Arpit Mandliya
 */
public class getHomeDirectoryMain {

	public static void main(String[] args)
	{
	
		String osName="";
		// Getting OS name
		osName = System.getProperty("os.name");
	
		System.out.println("--------------");
		
		System.out.println(osName);
		
		if (osName.toLowerCase().indexOf("win") >= 0) {
			System.out.println("You are using Windows");
		} else if (osName.toLowerCase().indexOf("mac") >= 0) {
			System.out.println("You are using MAC");
		} else if (osName.toLowerCase().indexOf("nix") >= 0 || osName.toLowerCase().indexOf("nux") >= 0 || osName.toLowerCase().indexOf("aix") > 0 ) {
			System.out.println("You are using Unix or Linux");
		} else if (osName.toLowerCase().indexOf("sunos") >= 0) {
			System.out.println("You are using Solaris");
		} else {
			System.out.println("Not able to detect OS");
		}
		
		System.out.println("--------------");
	}
}

I am using Mac os to run above program. When I ran above program, I got below output
--------------
Mac OS X
You are using MAC
--------------



In this post, we will see how to get user profile's home directory in java. It is quite simple, we can use System.getProperty("user.home") to get it.

Java program:

package org.arpit.java2blog;

/*
 * @Author Arpit Mandliya
 */
public class getHomeDirectoryMain {

	public static void main(String[] args)
	{
		System.out.println("--------------");
		String homeDirectory="";
		homeDirectory = System.getProperty("user.home");
		System.out.println("Home directory is : "+homeDirectory);
		System.out.println("--------------");
	}
}

When I ran above program, I got below output:
--------------
Home directory is : /Users/Arpit
--------------


In this post, we will see how to get current working directory in java.
There are two ways to do it.
  • Using property user.dir
  • Using getAbsolutePath()

Using property user.dir

We can use System.getProperty("user.dir") to get current working directory path.
package org.arpit.java2blog;

/*
 * @Author Arpit Mandliya
 */
public class getCurretWorkingDirectoryMain {

	public static void main(String[] args)
	{
		System.out.println("--------------");
		String currentWorkingDirectory;
		currentWorkingDirectory = System.getProperty("user.dir");
		System.out.println("Current working directory is : "+currentWorkingDirectory);
		System.out.println("--------------");
	}
}

When I ran above program, I got below output:
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir

Using getAbsolutePath()

We can use file.getAbos
package org.arpit.java2blog;

import java.io.File;

/*
 * @Author Arpit Mandliya
 */
public class getCurretWorkingDirectoryMain {

	public static void main(String[] args)
	{
		System.out.println("--------------");
		String currentWorkingDirectory="";
		// . denotes current working directory
		File file=new File(".");
		currentWorkingDirectory=file.getAbsolutePath();
		System.out.println("Current working directory is : "+currentWorkingDirectory);
		System.out.println("--------------");
	}
}

When I ran above program, I got below output:
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir/.




    In this post, we will see how to move file to another directory in java. We will use java.io.File 's rename(File dest) to do it.

    In below example, we will move config_new.properties from /Users/Arpit/Desktop/Folder1 to /Users/Arpit/Desktop/Folder2 .

    Java Program:

    package org.arpit.java2blog;
    
    import java.io.File;
    /*
     * @Author : Arpit Mandliya
     */
    public class MoveFileMain {
    
     public static void main(String[] args) {
      
      System.out.println("-----------------");
      //when source file is present
      File fileSrc = new File("/Users/Arpit/Desktop/Folder1/config_new.properties");
      File newFileDest = new File("/Users/Arpit/Desktop/Folder2/"+fileSrc.getName());
      if(fileSrc.renameTo(newFileDest)){
       System.out.println("Move operation is successful");
      }else{
       System.out.println("Move operation is unsuccessful");
      }
      System.out.println("-----------------");
      //when source file is not present
      File file = new File("/Users/Arpit/notExists.txt");
      File newFile = new File("xyz.txt");
      if(file.renameTo(newFile)){
       System.out.println("Move operation is successful");
      }else{
       System.out.println("Move operation is unsuccessful");
      }
      System.out.println("-----------------");
    
     }
    
    }
    
    
    When I ran above program, I got following output:
    -----------------
    Move operation is successful
    -----------------
    Move operation is unsuccessful
    -----------------
    

    In this post, we will see how to rename a file in java. We can use java.io.File 's rename(File dest) method to rename a file. rename method returns true if operation is success else returns false. It can use this method to move a file also.

    You should always check if rename operation is successful or not because it does not throw any exception

    Java Program:

    package org.arpit.java2blog;
    
    import java.io.File;
    
    public class RenameFileMain {
     /*
      * @Author : Aprit Mandliya
      */
    
     public static void main(String[] args) {
    
      System.out.println("-----------------");
      
      // Read the file
      File configFile=new File("/Users/Arpit/Desktop/config.properties");
      // destination file object
      File configFileNew=new File("/Users/Arpit/Desktop/config_new.properties");
      boolean remameSuccess=configFile.renameTo(configFileNew);
    
      if(remameSuccess)
      {
       System.out.println("Rename operation is successful");
      }
      else
      {
       System.out.println("Rename operation is unsuccessful");
      }
    
      System.out.println("-----------------");
     }
    
    }
    
    
    When I ran above program, I got following output:
    -----------------
    Rename operation is successful
    -----------------
    


    If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
    In this post, we will see how to find start node of loop in linkedlist in java. We have already seen how to detect a loop in linkedlist in java. This is extension of that post.

    Java Linked List Interview Programs:

      How to reverse a linked list in java How to reverse a linked list in pairs in java How to find middle element of linked list in java How to detect a loop in linked list in java Find start node of loop in linkedlist How to find nth element from end of linked list How to check if linked list is palindrome in java Add two numbers represented by linked list in java

    Algorithm:

    It is quite easy to find starting node of loop in linkedlist.
    • Find meeting point of slowPointer and fastPointer.
    • set slowPointer to head node of linkedlist.
    • Move slowPointer and fastPointer both by one node.
    • The node at which slowPointer and fastPointer meets, will be starting node of loop.
    public Node  findStartNodeOfTheLoop() {
      Node fastPtr = head;
      Node slowPtr = head;
      boolean loopExists=false;
      while (fastPtr != null && fastPtr.next != null) {
       fastPtr = fastPtr.next.next;
       slowPtr = slowPtr.next;
       if (slowPtr == fastPtr)
       {
        loopExists=true;
        break;
       }
    
      }
      if(loopExists)
      {
       slowPtr=head;
    
       while(slowPtr!=fastPtr)
       {
        slowPtr=slowPtr.next;
        fastPtr=fastPtr.next;
       }
    
       
      }
      else
      {
       System.out.println("Loop does not exists");
       slowPtr=null;
      }
      return slowPtr;
     }
    
    
    You must be wondering how above approach will work.

    Lets understand with help of example:

    As per above diagram:


    Distance travelled by slowPointer= A+B
    Distance travelled by fastPointer= (A+B+C) + B =A+2B+C

    Let speed of slow pointer be X , so speed of fast pointer will be 2*X
    As per simple distance speed, time relation:

    (A+B)/X=A+2B+C/2*X

    2*(A+B)=A+2B+C

    2A+2B=A+2B+C

    A=C

    Hence if we set slowPointer to head and move both slowPointer and fastpointer by one node, they will meet at start node of loop.

    Java code :

    package org.arpit.java2blog;
    
    public class LinkedList{
    
     private Node head;
    
     private static class Node {
      private int value;
      private Node next;
    
      Node(int value) {
       this.value = value;
    
      }
     }
    
     public void addToTheLast(Node node) {
    
      if (head == null) {
       head = node;
      } else {
       Node temp = head;
       while (temp.next != null)
        temp = temp.next;
    
       temp.next = node;
      }
     }
    
    
     public void printList() {
      Node temp = head;
      while (temp != null) {
       System.out.format("%d ", temp.value);
       temp = temp.next;
      }
      System.out.println();
     }
    
     public Node  findStartNodeOfTheLoop() {
      Node fastPtr = head;
      Node slowPtr = head;
      boolean loopExists=false;
      while (fastPtr != null && fastPtr.next != null) {
       fastPtr = fastPtr.next.next;
       slowPtr = slowPtr.next;
       if (slowPtr == fastPtr)
       {
        loopExists=true;
        break;
       }
    
      }
      if(loopExists)
      {
       slowPtr=head;
    
       while(slowPtr!=fastPtr)
       {
        slowPtr=slowPtr.next;
        fastPtr=fastPtr.next;
       }
    
       
      }
      else
      {
       System.out.println("Loop does not exists");
       slowPtr=null;
      }
      return slowPtr;
     }
    
    
     public static void main(String[] args) {
      LinkedList list = new LinkedList();
      // Creating a linked list
      Node loopNode=new Node(7);
      list.addToTheLast(new Node(5));
      list.addToTheLast(new Node(6));
      list.addToTheLast(loopNode);
      list.addToTheLast(new Node(1));
      list.addToTheLast(new Node(2));
    
      list.printList();
      list.addToTheLast(loopNode);  
    
      Node startNode=list.findStartNodeOfTheLoop();
      if(startNode!=null)
       System.out.println("start Node of loop is "+ startNode.value);
    
    
    
     }
    }
    
    
    When you run above program, you will get following output:
    5 6 7 1 2 
    start Node of loop is 7
    
    

    Please go through java interview programs for more such programs.

    In this post, we will see how to make a read only file in java. It is very simple. You need to just call java.io.File 's  setReadOnly() method.

    1) How to make a file read only

    Java program:

    package org.arpit.java2blog;
    
    import java.io.File;
    
    public class FileHiddenMain {
    
     public static void main(String[] args) {
      System.out.println("-----------------");
      // Read the file
      File configFile=new File("/Users/Arpit/Desktop/config.properties");
      configFile.setReadOnly();
      
      if(configFile.canWrite())
      {
       System.out.println("Config file can be writtern");
      }
      else
      {
       System.out.println("config file is read only");
      }
    
      System.out.println("-----------------");
    
                }
         }
    
    When you run above program, you will get following output:
    -----------------
    config file is read only
    -----------------
    

    2) How to make it writable  again

    If you have made file read only, you can make file writable again by using method setWritable(true).
    This method is introduced in java 1.6.

    Java program:

    package org.arpit.java2blog;
    
    import java.io.File;
    
    public class FileHiddenMain {
    
     public static void main(String[] args) {
      System.out.println("-----------------");
      // Read the file
      File configFile=new File("/Users/Arpit/Desktop/config.properties");
      configFile.setReadOnly();
      
      if(configFile.canWrite())
      {
       System.out.println("Config file can be written");
      }
      else
      {
       System.out.println("config file is read only");
      }
    
      System.out.println("-----------------");
    
      System.out.println("Making config file writable again");
      // this method is available from jdk 1.6
      configFile.setWritable(true);
      
      if(configFile.canWrite())
      {
       System.out.println("Config file can be written");
      }
      else
      {
       System.out.println("config file is read only");
      }
    
      System.out.println("-----------------");
     }
    
    }
    
    
    
    
    
    
    When you run above program, you will get following output:
    -----------------
    config file is read only
    -----------------
    Making config file writable again
    Config file can be written
    -----------------
    
    




    In this post, we will see how to import all classes at once in eclipse.

    Problem : 

    Sometimes you copy any java code from somewhere and you see many import errors. You go to each class and press ctrl + space to import each class one by one. Lets say you have large number of classes, you have to import each class one by one.

    Solution:

    Eclipse have provided organize imports feature which can import all classes at once and prompt you to select any class if there are multiple classes of same name present in classpath.
    Right click -> source -> organize imports

    Shortcut:

    ctrl + shift + o

    Lets understand with the help of example:




    You can see, we need to import lot of classes. Just press ctrl + shift + o, you will see below screen.



    Bingo!! you have resolved all import errors at once. I use this shortcut very often, I hope you find it useful.





    In this post, we will see how to read a file from resources folder in java. If you create a maven project(simple java or dynamic web project) , you will see folder src/java/resources. You can read from resources folder using these simple code.

     
                            // Getting ClassLoader obj
       ClassLoader classLoader = this.getClass().getClassLoader();
       // Getting resource(File) from class loader
       File configFile=new File(classLoader.getResource(fileName).getFile());
    

    Project structure:

    Java Program:

    package org.arpit.java2blog;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    /*
     * @author Arpit Mandliya
     */
    public class ReadPropertiesFileJavaMain {
    
     public static void main(String args[]) throws IOException
     {
      ReadPropertiesFileJavaMain rp=new ReadPropertiesFileJavaMain();
      System.out.println("Reading file from resources folder");
      System.out.println("-----------------------------");
    
      rp.readFile("config.txt");
      
      System.out.println("-----------------------------");
     }
    
     public  void readFile(String fileName) throws IOException
     {
      FileInputStream inputStream=null;
      
      try {
       // Getting ClassLoader obj
       ClassLoader classLoader = this.getClass().getClassLoader();
       // Getting resource(File) from class loader
       File configFile=new File(classLoader.getResource(fileName).getFile());
      
       inputStream = new FileInputStream(configFile);
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
       String line;
       while ((line = reader.readLine()) != null) {
       System.out.println(line);
       }
     
       reader.close();
    
    
      } catch (FileNotFoundException e) {
    
       e.printStackTrace();
      }catch (IOException e) {
    
       e.printStackTrace();
      }
      finally {
       inputStream.close();
      }
    
      
     }
    
    }
    
    
    When you run above program, you will get following output.
    Reading file from resources folder
    -----------------------------
    host = localhost
    username = java2blog
    password = java123
    -----------------------------
    

    Properties files are used in java projects to externalise configuration, for example, database settings. In this post , we will see how to read properties file in java.

    Java used Properties class to store above key values pair. Properties.load method is very convenient to load properties file in form of key values pairs.

    Properties file looks something like this.



    There are two ways you can do it.
    • Read properties file from system
    • Read properties file  from classpath

    Read properties file from System :

    In this, you need to read properties file from system path. Here I am putting properties file in root level of project.


    java code:
    package org.arpit.java2blog;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Properties;
    /*
     * @author Arpit Mandliya
     */
    public class ReadPropertiesFileJavaMain {
    
     public static void main(String args[]) throws IOException
     {
      System.out.println("Reading from properties file");
      System.out.println("-----------------------------");
      Properties prop=readPropertiesFile("config.properties");
      
      System.out.println("host : "+prop.getProperty("host"));
      System.out.println("username : "+prop.getProperty("username"));
      System.out.println("password : "+prop.getProperty("password"));
      System.out.println("-----------------------------");
     }
    
     public static Properties readPropertiesFile(String fileName) throws IOException
     {
      FileInputStream fis=null;
      Properties prop=null;
      try {
       fis= new FileInputStream(fileName);
       // create Properties class object
       prop=new Properties();
       // load properties file into it
       prop.load(fis);
    
      } catch (FileNotFoundException e) {
    
       e.printStackTrace();
      }catch (IOException e) {
    
       e.printStackTrace();
      }
      finally {
       fis.close();
      }
    
      return prop;
     }
    
    }
    
    
    When you run above program, you will get following output:
    Reading from properties file
    -----------------------------
    host : localhost
    username : java2blog
    password : java123
    -----------------------------
    
    

    Read properties file from classpath: 

    You can read properties file to classpath too. you have $project/src as default classpath as this src folder will be copied to classes. You can put it in $project/src folder and read it from there.


     you need to use
    this.getClass().getResourceAsStream("/config.properties");
    
    to read it from classpath.
    package org.arpit.java2blog;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    /*
     * @author Arpit Mandliya
     */
    public class ReadPropertiesFileJavaMain {
    
     public static void main(String args[]) throws IOException
     {
      ReadPropertiesFileJavaMain rp=new ReadPropertiesFileJavaMain();
      System.out.println("Reading from properties file");
      System.out.println("-----------------------------");
      
      Properties prop=rp.readPropertiesFile("/config.properties");
    
      System.out.println("host : "+prop.getProperty("host"));
      System.out.println("username : "+prop.getProperty("username"));
      System.out.println("password : "+prop.getProperty("password"));
      System.out.println("-----------------------------");
     }
    
     public  Properties readPropertiesFile(String fileName) throws IOException
     {
      InputStream fis=null;
      Properties prop=null;
      try {
       prop=new Properties();
       fis=this.getClass().getResourceAsStream(fileName);
      
       // create Properties class object
       if (fis != null) {
        // load properties file into it
        prop.load(fis);
       } else {
        throw new FileNotFoundException("property file '" + fileName + "' not found in the classpath");
       }
    
      } catch (FileNotFoundException e) {
    
       e.printStackTrace();
      }catch (IOException e) {
    
       e.printStackTrace();
      }
      finally {
       fis.close();
      }
    
      return prop;
     }
    
    }
    
    
    When you run above program, you will get following output:
    Reading from properties file
    -----------------------------
    host : localhost
    username : java2blog
    password : java123
    -----------------------------
    
    

    In this post, we will see how to read object from file in java. In last post, we have already seen how to write object to a file and created employee.ser , now in this post, we are going to read same file and retrieve back Employee object.

    Java Serialization Tutorial:

      Serialization in java Java Serialization interview questions and answers serialversionuid in java serialization externalizable in java Transient keyword in java Difference between Serializable and Externalizable in Java

    Reading object from file using ObjectInputStream may be referred as Deserialization.

    Steos for reading object from file are:

    Lets take an example:
    Create Employee.java same as last example in src->org.arpit.java2blog

    1.Employee.java
    package org.arpit.java2blog;
    import java.io.Serializable;
    public class Employee implements Serializable{ 
       private static final long serialVersionUID = 1L;    
      int employeeId;
        String employeeName;
        String department;
        
        public int getEmployeeId() {
            return employeeId;
        }
        public void setEmployeeId(int employeeId) {
            this.employeeId = employeeId;
        }
        public String getEmployeeName() {
            return employeeName;
        }
        public void setEmployeeName(String employeeName) {
            this.employeeName = employeeName;
        }
        public String getDepartment() {
            return department;
        }
        public void setDepartment(String department) {
            this.department = department;
        }
    }
    
    Create DeserializeMain.java in src->org.arpit.java2blog

    2.DeserializeMain.java
    package org.arpit.java2blog;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    
    public class DeserializeMain {
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
      
      Employee emp = null;
           try
           {
              FileInputStream fileIn =new FileInputStream("employee.ser");
              ObjectInputStream in = new ObjectInputStream(fileIn);
              emp = (Employee) in.readObject();
              in.close();
              fileIn.close();
           }catch(IOException i)
           {
              i.printStackTrace();
              return;
           }catch(ClassNotFoundException c)
           {
              System.out.println("Employee class not found");
              c.printStackTrace();
              return;
           }
           System.out.println("Deserialized Employee...");
           System.out.println("Emp id: " + emp.getEmployeeId());
           System.out.println("Name: " + emp.getEmployeeName());
           System.out.println("Department: " + emp.getDepartment());
     }
    }

    3.Run it:

    When you run above DeserializeMain.java and you will get following output:
    Deserialized Employee...
    Emp id: 101
    Name: Arpit
    Department: CS

    These are some simple steps to read object from file. If you want to go through some complex scenario you can go through Serialization in java
     

    Java tutorial for beginners Copyright © 2012