CSV Read in java

Friday, December 14, 2012

CSV, comma separated values, files are commonly used to transport large amounts of tabular data between either companies or applications that are not directly connected. The files are easily editable using common spreadsheet applications like Microsoft Excel.

Fields are separated by commas.
Records are separated with system end of line characters, CRLF (ASCII 13 Dec or 0D Hex and ASCII 10 Dec or 0A Hex respectively) for Windows, LF for Unix, and CR for Mac.
For this application you need one jar file
That is : javacsv.jar


CSVReadExample.java


/**
* File Name : CSVReadExample.java
* Created By : Nagaraju V
* Created Date : Aug 06, 2009
* Purpose : Reading Data from CSV formated file
*/
package com.raj.csv;

import com.csvreader.CsvReader;

/**
* @author nagarajuv
*
*/
public class CSVReadExample {

public static void main(String arg[]) throws Exception {
CsvReader reader = new CsvReader("employees.csv");
reader.readHeaders();
System.out.println("EmpID \t EmpName \t Salary \t Age \t Experiance \t MobileNo");
while (reader.readRecord()) {
String EmpID = reader.get("EmpID");
String EmpName = reader.get("EmpName");
String Salary = reader.get("Salary");
String Age = reader.get("Age");
String Exp = reader.get("Exp");
String MobileNo = reader.get("MobileNo");

System.out.println(EmpID+"\t"+EmpName+"\t"+Salary+"\t"+Age+"\t"+Exp+"\t"+MobileNo);
}
reader.close();
}
}

The following source code contains the jar files and code. Enjoy with that example
Image Hosted by ImageShack.us
Image Hosted by ImageShack.us

Java Related Softwares

Friday, December 7, 2012


Java 1.5.0

With several new pure Java applications now available, Sun's Java 2 Runtime Environment is a necessary addition to your collection.


download



Tomcat Server

Tomcat is a web server here u can down load the 5.x, 6.x version of aphache and jakarta


apache-tomcat-6.0.13

jakarta-tomcat-5.0.25



Edit Plus

EditPlus is distributed as Shareware. You can download freely from here


editplust2.0

Delete Directory recursively in windows, linux

Wednesday, September 26, 2012

I have seen that many people may encounter the situation to delete the CVS or SVN directory recursively when they want to move their project to another version controlling system. Below i have given script to do this in both linux and windows.

Windows: Just run the below scipt from command prompt. This script deletes specified folder recursively even though it is in folder which contains space in name.

FOR /F "tokens=*" %G IN ('DIR /B /AD /S *CVS*') DO RMDIR /S /Q "%G"

Linux: Just run the below scipt from bash.

find . -type d -name CVS -exec rm -rf '{}' \;

Java Beginners Practical Programms

Thursday, April 5, 2012


The following practical examples will be very useful for the beginners.

/*Override equals(),toString() in Employee*/

/**
 * @author nagarajuv
 *
 */
class Emp {
 
 int id;
 String name;
 float salary;

 public Emp() {
  id = 10115;
  name = "Raju";
  salary = 45000f;
 }

 public void setEmp(int id, String name, float salary)
 {
  this.id = id;
  this.name = name;
  this.salary = salary;
 }

 public boolean equals(Emp emp) {
  if ((this.id == emp.id) && (this.name == emp.name)
    && (this.salary == emp.salary))
   return true;
  else
   return false;
 }

 public void display() {
  System.out.println("\n Emp id " + id + "\n name " + name + "\n salary "
    + salary);
 }

 public int getId() {
  return id;
 }

 public String getName() {
  return name;
 }

 public float getSalary() {
  return salary;
 }

 public String toString() {
  return (" Id:" + getId() + ", Name: " + getName() + ", Salary: " + getSalary());
 }

 public static void main(String[] args) {
  Emp e = new Emp();
  e.display();
  Emp e1 = new Emp();
  e1.setEmp(10116, "Leela", 35000f);
  e1.display();
  System.out.println(" e,e1 are not equal -- "+e.equals(e1));
  Emp e2 = new Emp();
  e2.setEmp(10116, "Leela", 35000f);
  System.out.println(" e1,e2 are equal -- "+e1.equals(e2));
  String s1 = " Employee 1 details:" + e;
  System.out.println(s1);
  String s2 = " Employee 2 details:" + e;
  System.out.println(s2);
  String s3 = " Employee 3 details:" + e;
  System.out.println(s3);
 }
}


/*Create an interface: Printable – method print(),
Write a class Utility to have a method printAll( Printable []),
Pass different objects (Shapes & Animals) to printAll() to print them.*/

interface Printable {
 public void print();
}

class InterfaceUsage {

 public void printAll(Printable p[]) {
  for (int i = 0; i < p.length; i++) {
   p[i].print();
  }
 }

 public static void main(String[] args) {
  Printable p[] = new Printable[2];
  p[0] = new Animal();
  p[1] = new Shapes();
  InterfaceUsage utility = new InterfaceUsage();
  utility.printAll(p);
 }
}

class Animal implements Printable {
 public void print() {
  System.out.println("Animal class**** " + this);
 }
}

class Shapes implements Printable {
 public void print() {
  System.out.println("Shapes class**** " + this);
 }
}

/* Create a program that explains InstanceOf */
class InstanceOfDemo {
 public static void main(String[] args) {
  Error error = new Error();
  Exception exception = new Exception();
  System.out.print((exception instanceof Throwable) + ",");
  System.out.print(error instanceof Throwable);
 }
}
/* Create a program that explains extends in java */

class Spr {
 private void print1() {
  System.out.print("Spr.print1 ");
 }

 protected void print2() {
  System.out.print("Spr.print2 ");
 }

 protected void printS1S2() {
  print1();
  print2();
 }
}

class Sub extends Spr {
 private void print1() {
  System.out.print("Sub.print1 ");
 }

 protected void print2() {
  System.out.print("Sub.print2 ");
 }

 public static void main(String[] args) {
  new Sub().printS1S2();
 }
}

/*What are user-defined exceptions? Create a user-defined exception
 called InvalidUserException. Create a class called Elections.
 Write a method called validityCheck with an integer argument called age. 
 Write your logic such that an exception is raised (use throw) when age is less than 18.*/

class InvalidUserException extends Exception {
 public InvalidUserException() {
  System.out.println("you are too young to vote");
 }
}

class UserDefinedExceptionDemo
{
 public void validityCheck(int n) {
  if (n < 18) {
   try {
    throw new InvalidUserException();
   }
   catch (InvalidUserException e) {
    System.out.println("invalid age" + e);
    e.printStackTrace();
   }
  }
 }

 public static void main(String[] args) {
  UserDefinedExceptionDemo exceptionDemo = new UserDefinedExceptionDemo();
  exceptionDemo.validityCheck(17);
 }
}
/*Create an InsufficientBalanceException to be thrown by withdraw() method in
Account class if amount to be withdrawn is greater than balance.*/

class InsufficientBalanceException extends Exception {
 float n;

 public InsufficientBalanceException(float n) {
  this.n = n;
 }
}

class Acc {
 float amt = 0;
 float bal = 200;

 public void withdraw(float amt) {
  bal = bal - amt;
  try {
   if (amt > bal)
    throw new InsufficientBalanceException(amt);
  } catch (InsufficientBalanceException e) {
   System.out.println("the withdrawal amount is greater than balance"
     + e);
   e.printStackTrace();
  }
  System.out.println(bal);
 }

}

class BankUserException {
 public static void main(String[] args) {
  Acc d1 = new Acc();
  d1.withdraw(500);
 }
}
/*Write a program that generates a StackOverFlowError and
 OutOfMemoryError ?*/

class StackOverFlowDemo {
 public static int sta() {
  return sta();
 }

 public static void main(String[] args) {
  sta();
 }
}
/*Create code snippets using all constructors of Wrapper Classes. 
Verify the output for different arguments of these constructors.*/

class WrapperClassConstructor
{
 public static void main(String[] args)
 {
  Boolean wboo = new Boolean("false");
  System.out.println(wboo);
  Boolean yboo=new Boolean(false);
  System.out.println(yboo);
  Byte wbyte = new Byte("2");
  System.out.println(wbyte);
  Short wshort = new Short("4");
  System.out.println(wshort);
  Integer wint = new Integer("16");
  System.out.println(wint);
  Integer yint = new Integer(16);
  System.out.println(yint);
  Long wlong = new Long("123");
  System.out.println(wlong);
  Long ylong = new Long(123);
  System.out.println(ylong);
  Float wfloat = new Float("12.34f");
  System.out.println(wfloat);
  Float yfloat = new Float(12.34f);
  System.out.println(yfloat);
  Double wdouble = new Double("12.56d");
  System.out.println(wdouble);
  Double ydouble = new Double(12.56d);
  System.out.println(ydouble);
  Character c1 = new Character('c');
  System.out.println(c1);
 }
} 
/*Call System.gc(), check whether GC runs or not*/

class FinalizeDemo {
 public void finalize() {
  System.out.println("finalize is getting called");
 }

 public static void main(String[] args) {
  FinalizeDemo finalize = new FinalizeDemo();
  FinalizeDemo finalize1 = new FinalizeDemo();
  finalize = finalize1;
  System.gc();
  System.out.println("hello world");
 }
} 
/* Thread by Thread class */
public class ThreadByThreadClass extends Thread {
 public ThreadByThreadClass() {
  System.out.println("ThreadByThreadClass");
 }

 public void run() {
  System.out.println("Threading by extension");
 }

 public static void main(String[] args) {
  Thread thread = new ThreadByThreadClass();
  thread.start();
 }
} 
/* Thread by Runnable Interface*/
public class ThreadByRunnable implements Runnable {
 public void run() {
  System.out.println("Implementing run method");
 }

 public static void main(String[] args) {
  new Thread(new ThreadByRunnable()).start();
 }
} 
/*Two members of a joint Account are trying to withdraw Rs.3000 from the account
simultaneously & balance is Rs.5000.
Create a Multi threaded program to handle this situation*/

class ThreadAccount extends Thread {
 private float balance;
 private float amount;
 
 public ThreadAccount(float bal, float amt) {
  this.balance = bal;
  this.amount = amt;
  
  // Thread JM1,JM2;
  Thread JM1 = new Thread(this, "JM1");
  Thread JM2 = new Thread(this, "JM2");

  JM1.start();
  JM2.start();
 }

 synchronized public void withDraw()
 { 
  System.out.println("Current Thread -- "+Thread.currentThread().getName());
  if (balance < amount){
   System.out.println("Low balance " + balance
     + " The amount trying to draw is " + amount);
  } 
  else{ 
   balance = balance - amount;
   System.out.println("With drawl amount is "+amount+" Available balance is " + balance);
  }
 }

 public void run() {
  this.withDraw();
 }

 public static void main(String[] args) {
  ThreadAccount threadAccount = new ThreadAccount(5000, 3000);
 }
} 
//Demonstration of scanner 

import java.util.Scanner;

class ScanrDemo {
 public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  System.out.println(" Enter the input");

  int d = input.nextInt();
  System.out.println("The entered integer is " + d);
 }
} 
//create a program to calculate the balance and withdrawal in a class called account.
/*Serialize & deserialize Account object which will have
 a Date type of field : doc (date of creation)*/
import java.io.*;

class Account implements Serializable {
 private static final long serialVersionUID = 1L;
 
 float amt = 0;
 float bal = 0;

 public void deposit(float amt)
 {
  bal = amt + bal;
  System.out.println("Balance after deposit : "+bal);
 }

 public void withdraw(float amt)
 {
  bal = bal - amt;
  System.out.println("Balance after withdraw : "+bal);
 }
}

class SerializeUserObj {

 public static void main(String[] args) throws Exception
 {
  Account account = new Account();

  account.deposit(1000);
  account.withdraw(800);
  FileOutputStream fos = new FileOutputStream("Account");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(account);
  oos.close();

  FileInputStream fis = new FileInputStream("Account");
  ObjectInputStream ois = new ObjectInputStream(fis);
  account = (Account) ois.readObject();
  System.out.println(account.amt);
  System.out.println(account.bal);
  fis.close();
 }
} 
import java.io.*;

/*Write a program to create a file and write some content into it 
 Read the created file and print the contents of the file on the output screen?*/

public class FileReadWriteDemo {
 public static void main(String[] args) throws Exception {

  // Reading data from keyboard
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter the contents to a file :");
  String inputData = in.readLine();
  // Writing data to a file "SampleFile.txt"
  FileWriter fstream = new FileWriter("SampleFile.txt");
  BufferedWriter out = new BufferedWriter(fstream);
  out.write(inputData);
  out.close();
  // Reading data from file "SampleFile.txt"
  FileInputStream fis = new FileInputStream("SampleFile.txt");
  DataInputStream dis = new DataInputStream(fis);
  BufferedReader br = new BufferedReader(new InputStreamReader(dis));
  String line;
  // Displaying read data to console
  while ((line = br.readLine()) != null)
  {
   System.out.println(line);
  }
  dis.close();
 }
} 
/* Tree set demo */
class TreeSetDemo {
 public static void main(String[] args) {
  Set set = new TreeSet();

  set.add("Z");
  set.add("A");
  set.add("F");
  set.add("B");
  set.add("H");
  set.add("X");
  set.add("N");
  for (String item : set) {
   System.out.print(item + " ");
  }
 }
} 
//Create a sorted set of Employee objects.(Sort on Emp ID)

import java.util.*;

class Empar implements Comparable{


 private Integer id;
 private String name;
 private double salary;

 public Empar(Integer id, String name, double salary) {
  this.id = id;
  this.name = name;
  this.salary = salary;
 }
 
 public Integer getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 public double getSalary() {
  return salary;
 }

 public void setSalary(double salary) {
  this.salary = salary;
 }
 /*public String toString() {
  return ("Name: " + name + " Id:" + id + " Salary: " + salary);
 }*/

 @Override
 public int compareTo(Empar emp) {
  return this.getId().compareTo(emp.getId());
 }
}

public class SortEmpObjById {

 public static void main(String[] args) {
  Empar e[] = new Empar[3];
  e[0] = new Empar(10119, "Raju", 45000d);
  e[1] = new Empar(10116, "Vidya", 50000d);
  e[2] = new Empar(10117, "Mahesh", 53000d);
  System.out.println("List of employees before sort ");
  for (int i = 0; i < 3; i++) {
   //System.out.println(e[i]);
   Empar emp = e[i];
   System.out.println("Name: " + emp.getName() + " Id:" + emp.getId() + " Salary: " + emp.getSalary());
  }
  
  Set set = new TreeSet();
  set.add(e[0]);
  set.add(e[1]);
  set.add(e[2]);
  
  System.out.println("List of employees after sort based on Id");
  for(Empar emp : set)
  {
   System.out.println("Name: " + emp.getName() + " Id:" + emp.getId() + " Salary: " + emp.getSalary());
  }
 }
}

/**
 * MySql Connection Test
 */
package com.raj.DBtest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author nagarajuv
 * 
 */
public class MysqlConnTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Connection con = null;
  Statement s = null;
  ResultSet rset = null;
  try {
   Class.forName("com.mysql.jdbc.Driver");
   con = DriverManager.getConnection(
     "jdbc:mysql://localhost:3306/mydbtest", "raju", "raju");
   s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
     ResultSet.CONCUR_READ_ONLY);
   rset = s.executeQuery("select * from emp");
   while (rset.next()) {
    System.out.println(" " + rset.getInt("eid") + " "
      + rset.getString("ename"));
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (rset != null) {
     rset.close();
    }
    if (s != null) {
     s.close();
    }
    if (con != null) {
     con.close();
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
}

Tags:Java Beginners, Java Practical Examples, Override equals(), Override toString(), InterfaceUsage, InstanceOf, extends in java, user defined Exceptions, StackOverFlowError Demo, User defined Exception Example with Bank, Wrapper class constructors, Finalize demo example, Thread by extending Thread Class, Thread by implementing Runnable Interface, Thread Synchronization example, Usage of synchronized method in java, scanner in java, serialize and deserialize in java, reading and writing data to from file, reading data from keyboard, sorting obj based on it's property, comparable example, My sql Database Connection, Connection test.