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;
	}
}

[My Video Promotion]
  1. How to extract plain Text from HTML Website easily in Java
  2. Binary Search Implementation In Java
  3. Simple Implemenation Of Stack In Java Using Vector
  4. How To Find What Java Version You Are Using?
  5. Computing the total, free and usable disk space easily using JDK 1.6
  6. Creating java.util.date and java.util.sql objects from Calendar object
  7. Bar Code Generation In Java Using iText API
  8. Simple Tag Generator In Java For Music Blogs
  9. Tutorial on Converting an List of Strings or Numbers to a CSV file with optional sorting
  10. Calling URL Browser From Java Application
  11. Java Reflection Tutorial – List Methods Of A Class
  12. Cleaning Punctuation And White Spaces From A String
  13. Java Tutorial – Using JCIFS to copy files to shared network drive using username and password
  14. Prime Number Finder In Java
  15. Utility Class For Getting SQL Connection and Closing It
  16. Java Design Pattern – Singleton Pattern
  17. Reading / Writing File in Java and String Manipulation
  18. How to capture a screenshot using Java and save it to a file?
  19. Calculating The Difference Between Two Dates In Terms of Months
  20. Getting The Name Of Currently Logged In User In The System
  21. How To Set And Get System Clipboard Contents In Java
  22. RGB To Hex and Hex To RGB Conversion Using Java and Regular Expressions
  23. Java Code Implementation Of Selection Sort
  24. Generating Nepali Unicode Sequence For Characters
  25. Java Tool To Compare Two Lists and Spit Out The Differences – Working Example
  26. Replacing non-ASCII characters using Java Regular Expressions
  27. Calculating Folder Size In Java
Tagged , , , , , , , , . Bookmark the permalink.

3 Responses to Calculating Folder Size In Java

  1. Pingback: Sanjaal.com » Latest Updates

  2. Jamie says:

    This approach uses less memory:

    public static class SizeCounter implements FileFilter
    {
    private long total = 0;
    public SizeCounter(){};
    public boolean accept(File pathname) {
    if ( pathname.isFile()) {
    total+=pathname.length();
    } else {
    pathname.listFiles(this);
    }
    return false;
    }
    public long getTotal()
    {
    return total;
    }
    }

    private static long getFileOrDirectorySize(File file) {
    SizeCounter counter = new SizeCounter();
    file.listFiles(counter);
    return counter.getTotal();
    }

  3. kushalzone says:

    Thank you Jamie for your optimized solution.

Leave a Reply to kushalzone Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.