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.

No comments:

Post a Comment