Tutorial on Converting an List of Strings or Numbers to a CSV file with optional sorting

Chances are you might have needed to convert a list of strings or numbers to a CSV file while you were programming something. An example is that in any java program you might have obtained a list of states of United States stored in your ArrayList object and then you wanted to have them in a CSV format so that you probably could load it to a database or use it for some other purposes.

I wrote this tool to serve the same purpose.

Here are the basic features this simple java example can do. Given a list of String objects stored in an ArrayList, this program can:

  • Convert Strings or numbers stored in an ArrayList object to comma separated strings
  • Print the comma separated values (CSV) to either console or file
  • Optionally you can sort the the list before you do the conversion.

package com.kushal.tools;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @author Kushal Paudyal 
 * Last Modified on 2011-09-06 This utility converts a
 * list to comma separated values. Intended to be used with Strings and
 * can be modified with numbers.
 * 
 * Have options to write the converted values to either console or file.
 */
public class ListToCSV {
	private static boolean writeCSVToConsole = true;
	private static boolean writeCSVToFile = true;
	private static String destinationCSVFile = "C:\temp\convertedCSV.csv";
	private static boolean sortTheList = true;

	public static void main(String[] args) {
		ListToCSV util = new ListToCSV();
		List<String> sampleList = util.createSampleList();
		util.convertAndPrint(sampleList, writeCSVToConsole, writeCSVToFile, sortTheList);

	}

	/**
	 * @param sampleList - input list of string
	 * @param writeToConsole - if this flag is true, writes to console
	 * @param writeToFile - if this flag is true writes to file.
	 * @param sortTheList - if the list is to be sorted before conversion
	 */
	private void convertAndPrint(List<String> sampleList,
			boolean writeToConsole, boolean writeToFile, boolean sortTheList) {
		String commaSeparatedValues = "";

		/** If the list is not null and the list size is not zero, do the processing**/
		if (sampleList != null) {
			/** Sort the list if sortTheList was passed as true**/
			if(sortTheList) {
				Collections.sort(sampleList);
			}
			/**Iterate through the list and append comma after each values**/
			Iterator<String> iter = sampleList.iterator();
			while (iter.hasNext()) {
				commaSeparatedValues += iter.next() + ",";
			}
			/**Remove the last comma**/
			if (commaSeparatedValues.endsWith(",")) {
				commaSeparatedValues = commaSeparatedValues.substring(0,
						commaSeparatedValues.lastIndexOf(","));
			}
		}
		/** If writeToConsole flag was passed as true, output to console**/
		if(writeToConsole) {
			System.out.println(commaSeparatedValues);
		}
		/** If writeToFile flag was passed as true, output to File**/		
		if(writeToFile) {
			try {
				FileWriter fstream = new FileWriter(destinationCSVFile, false);
				BufferedWriter out = new BufferedWriter(fstream);
				out.write(commaSeparatedValues);
				out.close();
				System.out.println("*** Also wrote this information to file: " + destinationCSVFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * Creates a sample list to be used by the convertAndPrint method
	 * and returns it to the calling method. 
	 */
	private List<String> createSampleList() {
		List<String> sampleList = new ArrayList<String>();
		sampleList.add("Nebraska");
		sampleList.add("Iowa");
		sampleList.add("Illinois");
		sampleList.add("Idaho");
		return sampleList;
	}
}

Calling URL Browser From Java Application

This program teaches you how you can call the browser in your OS to open the URL that you are passing from your Java application. This program is fully compiled and tested.

package com.kushal.utilities;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 26th August, 2008
 */
import java.lang.reflect.Method;

import javax.swing.JOptionPane;

public class OpenDefaultBrowserFromJava {
	private static final String errMsg = "ERROR WHILE ATTEMPTEING TO LUNCH WEB BROWSER";
	private static final String errFindingBrowser="COULD NOT FIND THE BROWSER";
	
	public static void main(String args [])
	{
		String urlToOpen="http://www.sanjaal.com/java";
		openURL(urlToOpen);
	}

	/**
	 * This method takes URL as a parameter and tries to
	 * identify Operating system and then lunches the broswer
	 * with the given URL
	 */
	public static void openURL(String url) {
		String operatingSystem = System.getProperty("os.name");
		try {
			/*
			 * Check if it is windows OS 
			 */
			if (operatingSystem.startsWith("Windows"))
				Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
			/*
			 * If not windows OS, Check if it is a Mac OS
			 */
			else if (operatingSystem.startsWith("Mac OS")) {
				Class fileManager = Class.forName("com.apple.eio.FileManager");
				Method openURL = fileManager.getDeclaredMethod("openURL",
						new Class[] { String.class });
				openURL.invoke(null, new Object[] { url });
			}
			
			/*
			 * Or, it might be some unix or linux OS
			 */
			else { 
				/**
				 * There are different browsers possible.
				 */
				String[] browsers = { 	"firefox", 
										"netscape",
										"opera", 
										"konqueror", 
										"epiphany", 
										"mozilla"};
				String browser = null;
				
				for (int count = 0; count < browsers.length && browser == null; count++)
					if (Runtime.getRuntime().exec(
							new String[] { "which", browsers[count] })
							.waitFor() == 0)
						browser = browsers[count];

				if (browser == null) 
					throw new Exception(errFindingBrowser);
				else
					Runtime.getRuntime().exec(new String[] { browser, url });
			}

		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, errMsg + ":n" + e.getMessage());
		}
	}

}

Java Reflection Tutorial – List Methods Of A Class

Reflection is a very powerful tool in Java. I will start this tutorial with an excerpt from Sun’s Tutorial Page for Java reflections. It says:

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

  • Extensibility Features
    An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
  • Class Browsers and Visual Development Environments
    A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.
  • Debuggers and Test Tools
    Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

Drawbacks of Reflection
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

  • Performance Overhead
    Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
  • Security Restrictions
    Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
  • Exposure of Internals
    Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

The following tutorial will use the class called Student and display all the methods of that class using the Java Reflection technology.

package com.kushal.utils;
/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 10th August 2009
 *
 * A Simple class that lists the method of another
 * class using the reflections mechanism.
 */
import java.lang.reflect.Method;

public class MethodsListViaReflection {

	public void listMethods() {

		Class myStudentClass = Student.class;

		Method[] methods = myStudentClass.getDeclaredMethods();

		for (Method method : methods) {
			System.out.println(method.getName());
		}
	}

	public static void main(String[] args) {
		new MethodsListViaReflection().listMethods();
	}
}

class Student {

private String _firstname;
private String _lastname;
private String _address;
private int _rollNumber;

public String getFirstname() {
return _firstname;
}

public void setFirstname(String firstname) {
_firstname = firstname;
}

public String getLastname() {
return _lastname;
}

public void setLastname(String lastname) {
_lastname = lastname;
}

public String getAddress() {
return _address;
}

public void setAddress(String address) {
_address = address;
}
public int getRollNumber() {
return _rollNumber;
}

public void setRollNumber(int rollNumber) {
_rollNumber= rollNumber;
}
}[/java]
=======================
The following is the output of this program:
getFirstname
setFirstname
getLastname
setLastname
getAddress
setAddress
getRollNumber
setRollNumber