Java – Generate CSV from Java Bean using OpenCSV

Download OpenCSV: http://sourceforge.net/projects/opencsv/files/latest/download

OpenCSV is a free and open source library for reading and writing CSV files in Java. We need to have latest opencsv jar in classpath. Following example shows generating a CSV from java beans using opencsv.

Bean2CSV.java

import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;

import au.com.bytecode.opencsv.CSVWriter;

public class Bean2CSV {

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

    Student stud1 = new Student("Mayur", 25);
    Student stud2 = new Student("Vishal", 26);
    List<Student> students = Arrays.asList(stud1, stud2);

    StringWriter sw = new StringWriter();
    CSVWriter writer = new CSVWriter(sw);

    //Write header
    String [] header = { "name", "age" };
    writer.writeNext(header);

    //Write data
    String [] data;
    for (Student s : students) {
      data = new String [] { s.getName(), String.valueOf(s.getAge()) };
      writer.writeNext(data);
    }
    writer.close();

    System.out.println("Generated CSV : \n");
    System.out.println(sw.toString());
  }
}

Student.java

public class Student {

  private String name;
  private int age;

  public Student() {
  }

  public Student(String name, int age) {
    super();
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }

  public String toString() {
    return "Student[name = " + name + ", age = " + age + "]";
  }
}

Output:

Generated CSV :
“name”,”age”
“Mayur”,”25″
“Vishal”,”26″

Java – Generic Interface Example

MinMax.java

interface MinMax<T extends Comparable<T>> {
  T min();
  T max();
}

MyClass.java

class MyClass<T extends Comparable<T>> implements MinMax<T> {
  T[] vals; 

  MyClass(T[] o) { vals = o; } 

  public T min() {
    T v = vals[0];
    for(int i=1; i < vals.length; i++)
      if(vals[i].compareTo(v) < 0) v = vals[i]; 

    return v;
  } 

  public T max() {
    T v = vals[0]; 

    for(int i=1; i < vals.length; i++)
      if(vals[i].compareTo(v) > 0) v = vals[i]; 

    return v;
  }
}

GenIFDemo.java

public class GenIFDemo {
  public static void main(String args[]) {
    Integer inums[] = {3, 6, 2, 8, 6 };
    Character chs[] = {'b', 'r', 'p', 'w' }; 

    MyClass<Integer> iob = new MyClass<Integer>(inums);
    MyClass<Character> cob = new MyClass<Character>(chs); 

    System.out.println("Max value in inums: " + iob.max());
    System.out.println("Min value in inums: " + iob.min()); 

    System.out.println("Max value in chs: " + cob.max());
    System.out.println("Min value in chs: " + cob.min());
  }
}

Java Struts – Logging with Log4j Example

Download Log4j: http://logging.apache.org/log4j/index.html

Log4j Appender:
Create a Log4j properties file (log4j.properties) and define the appender details (where to log and log file details). And put the log4j.properties into your project classpath.

log4j.properties

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Root logger option
log4j.rootLogger=error, file, stdout

Struts Action Class:

//...
public class UserAction extends Action{

  private static final Logger logger = Logger.getLogger(UserAction.class);

  public ActionForward execute(ActionMapping mapping,ActionForm form,
	HttpServletRequest request,HttpServletResponse response)
  throws Exception {

	if(logger.isDebugEnabled()){
		logger.debug("Starting started");
	}
	//...

Struts Custom Exception Handler:

//...
public class MyCustomExceptionHandler extends ExceptionHandler{

  private static final Logger logger =
                       Logger.getLogger(MyCustomExceptionHandler.class);

  @Override
  public ActionForward execute(Exception ex, ExceptionConfig ae,
	ActionMapping mapping, ActionForm formInstance,
	HttpServletRequest request, HttpServletResponse response)
	throws ServletException {

	//log the error message
	logger.error(ex);

	return super.execute(ex, ae, mapping, formInstance, request, response);
  }

}

Log4j Output File Sample- c:\\logging.log

12:45:52,210 ERROR MyCustomExceptionHandler:25 - java.io.IOException
12:48:27,672 ERROR MyCustomExceptionHandler:25 - ExceptionConfig[type=
java.io.IOException,handler=
com.javac.common.exception.MyCustomExceptionHandler,
key=error.global.mesage,path=/pages/error.jsp,scope=request]
12:48:54,102  INFO PropertyMessageResources:209 - Operating in Default mode [null]
12:48:54,134 DEBUG sax:1410 - startElement(,web-app,web-app)
12:48:54,134 DEBUG Digester:1417 -   Pushing body text ''
12:48:54,134 DEBUG Digester:1436 -   New match='web-app'
12:48:54,134 DEBUG Digester:1464 -   No rules found matching 'web-app'.

Page 5 of 49« First...34567...102030...Last »