Java Snippets

Monday, April 7, 2014

Calculate Number of Years between 2 Calendar Dates

Here is a function that calculates the number of years between 2 calendar dates:

public static double  yearsBetween(Calendar cal1, Calendar cal2){
        double dmsyear = 1000L * 60 * 60 * 24 * 365;
        return (cal1.getTimeInMillis()- cal2.getTimeInMillis())/dmsyear;
}   

You could call the method and format the result as String as follows:

Calendar cal1 = GregorianCalendar.getInstance();
Calendar cal2 = GregorianCalendar.getInstance();
cal2.set(2009,7,1);
String.format("%.1f years", yearsBetween(cal1, cal2));

Related posts:
Determine Next Month in Java

Friday, May 13, 2011

Surround Strings with Quotes

The following Java class adds quotes to a string depending on
whether it is a number or not. The class relies on the NumberFormatException to determine whether a string is a number.
The added benefit is that single quotes in strings are escaped with a backslash.


public class Util {
 public static String escapeQuotes( String s ){
      return s.replaceAll("'","\\\\'");
 }
 private static boolean isNumber(String str){
  try{
   Integer.parseInt(str);
   return true;
  }
  catch(NumberFormatException e){
   return false;
  }
 }
 private static boolean isEmpty(String str){
  return !(str.length()>0);
 }
 public static String addQuotes(String str) {
  str = str.trim();
  if(!isEmpty(str)){
   if(isNumber(str))
    return str;
   else
    return "'"+ escapeQuotes(str)+"'";
  }
  else
   return null;
 }

 public static String deleteLastCharacter(String str){
   return str.substring(0, str.length()-1);
 }
}
This class could be used as a helper class to construct a valid sql statement.
Here is code for a method that takes file contents and adds single quotes around Strings leaving numbers intact:
public static void convert (BufferedReader in, PrintWriter out)
   throws IOException {
 String separator  = System.getProperty("line.separator");
 String delimiter  = ",";
 for (String line = in.readLine(); line != null; line = in.readLine()) {
  line = line.trim();
  if (line.length() == 0) {
   continue;
  }
  StringTokenizer st = new StringTokenizer(line, delimiter, false);
  String outLine ="";
  while(st.hasMoreTokens()) {
   String token  = st.nextToken();
   outLine += Util.addQuotes(token) +",";
  }
  outLine = Util.deleteLastCharacter(outLine);
  out.print(outLine + separator);
  }
 in.close();
 out.close();
}

As you can see, this method accepts 2 arguments, BufferedReader and PrintWriter. It takes each line in a file and splits it into
comma-separated tokens. Then, addQuotes() method is called on each token. The line is assembled again and written to a PrintWriter.

Java Text File Splitter Class

Here is a Java class that splits a text file into multiple files using a supplied string as a separator.

It accepts two arguments in the constructor: a path to the file, and a token to be used for separation.

Usage example:

TextFileSplitter tfs = new TextFileSplitter('myfile.txt', 'Section');
tfs.run();

It will create a sub-directory in the same directory as the file where it will place the resulting files.

This is a very basic version that does not throw any exceptions.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

public class TextFileSplitter {

 private static String fullPath ;
 private static String token;

 public TextFileSplitter(String path, String token) {
  this.fullPath = path;
  this.token = token;
 }


 public void run(){

  ArrayList al = splitIntoTokens(fullPath, token);

  if(al.size()==0){
   return;
  }
  String dir = getDirectoryFromFileName(fullPath);

  int pageIndex =1;
  Iterator iter = al.listIterator();
  String name = getFileName(fullPath);

  while(iter.hasNext()){
   String str = (String)iter.next();
   String fileName = dir+"\\"+ name + "_"+ pageIndex + ".txt";
   try {
    System.out.println(fileName);
    writeFile(fileName, str);
   }
   catch (IOException e) {
    e.printStackTrace();
   }
   pageIndex++;
  }
 }


 private String getFileName(String path){

  String fileName = null;
  String separator = File.separator;

  int pos = path.lastIndexOf(separator);
  int pos2 = path.lastIndexOf(".");

  if(pos2>-1)
   fileName =path.substring(pos+1, pos2);
  else
   fileName =path.substring(pos+1);

  return fileName;
 }

 private String getDirectoryFromFileName(String fname) {

  String parent =  (new File(fname).getParent());

  String name = getFileName(fname);

  String dirPath = parent+"\\" + name;

  File dir = new File(dirPath);

  if(!dir.exists()){
   boolean success = dir.mkdir();
   if (!success) {
    System.out.println("Directory creation failed");
    return null;
   }
  }
  return dirPath;
 }




 private  void writeFile(String fname, String str) throws IOException{
  BufferedWriter out=new BufferedWriter ( new FileWriter(fname));
  out.write(str);
  out.close();
 }
 
 //splits a file into an ArrayList of strings using the separator passed
 
 private ArrayList splitIntoTokens(String fname, String token){
  String line;
  StringBuffer sb = new StringBuffer();
  ArrayList al = new ArrayList();
  String lineSeparator =  System.getProperty("line.separator");
  try {
   FileInputStream fis = new FileInputStream(fname);
            BufferedReader reader=
              new BufferedReader
                (new InputStreamReader(fis));

            while((line = reader.readLine()) != null) {
    if((line.indexOf(token))>-1){
     al.add(sb.toString());
     sb = new StringBuffer();
    }
    sb.append(line + lineSeparator);
   }
            //add last section
            al.add(sb.toString());
   reader.close();
  }
  catch (IOException e) {
            System.err.println("*** IOexception ***" + e.getMessage());
  }
  return al;

 }
}

List Files in a Directory

The following Java example returns an ArrayList of only those files that have a .csv extension.

public static ArrayList listFiles(String dirName) {
 ArrayList al = new ArrayList();
 File dir = new File(dirName);

 String[] children = dir.list(filter);
 if (children == null) {
//Either dir does not exist or is not a directory
  }
 else {
  for (int i = 0; i < children.length; i++) {
  // Add the file name to ArrayList
   al.add(children[i]);
  }
 }
  return al;
}

// Create an an inner class that implements the FilenameFilter interface.
    static FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith("csv");
        }
    };

To list all files in the directory use the list() method without arguments.

The code is based on the Java Developers Almanac .

Read File Contents into Java ArrayList

The following method reads file contents into an ArrayList. Each element of the ArrayList will contain a line from the file.

public ArrayList readFile(String fname){
    String line;
    StringBuffer sb = new StringBuffer();
    ArrayList al = new ArrayList();
    try {
     FileInputStream fis = new FileInputStream(fname);
        BufferedReader reader=
          new BufferedReader
            (new InputStreamReader(fis));
        while((line = reader.readLine()) != null) {
   al.add(line);
  }
        reader.close();
 }
 catch (IOException e) {
     System.err.println("*** IOexception ***" + e.getMessage());
 }
 return al;
 }

Get File Name without extension from Its Path

The following Java method returns a file name without extension from its path.

public static String getFileName(String path){

 String fileName = null;
 String separator = File.separator;

 int pos = path.lastIndexOf(separator);
 int pos2 = path.lastIndexOf(".");

 if(pos2>-1)
  fileName =path.substring(pos+1, pos2);
 else
  fileName =path.substring(pos+1);

 return fileName;
}
 

Create Sub-Directory From File Name in Java

Description:
You have a file name and you need to create a new directory in the folder where the file resides.

Solution:
The following method creates a new directory in the same directory as the file. If the directory exists already, it does nothing.
In other words, it makes sure the directory is there.
It accepts two strings as arguments, file name and sub-directory name.
boolean  createDirectory (String fname, String dirName) {
 //get the path to the parent directory
 String parent =  (new File(fname).getParent());
 //construct a new directory path
 String dirPath = parent+"\\" + dirName;

 File dir = new File(dirPath);

 if(!dir.exists()){
  boolean success = dir.mkdir();
  if (!success) {
   System.out.println("Directory creation failed");
   return false;
  }
 }
 return true;
}

A variation of the above method is the one that returns the path to the sub-directory:
public static String getDirectory(String fname, String dirName) {

  String parent =  (new File(fname).getParent());
  String dirPath = parent+"\\" + dirName;
  File dir = new File(dirPath);

  if(!dir.exists()){
   boolean success = dir.mkdir();
   if (!success) {
    System.out.println("Directory creation failed");
    return null;
   }
  }
  return dirPath;
 }



Another thing we could do is have the method create a sub-directory based on the file name without extension.
public static String getDirectoryFromFileName(String fname) {

  String parent =  (new File(fname).getParent());
  //extract a file name without extension from the path
  String name = getFileName(fname);
  String dirPath = parent+"\\" + name;

  File dir = new File(dirPath);

  if(!dir.exists()){
   boolean success = dir.mkdir();
   if (!success) {
    System.out.println("Directory creation failed");
    return null;
   }
  }
  return dirPath;
 }