Csv Converter : CSV File « Development Class « Java






Csv Converter

    

/*
 * 
 * Copyright (c) 2004 SourceTap - www.sourcetap.com
 *
 *  The contents of this file are subject to the SourceTap Public License 
 * ("License"); You may not use this file except in compliance with the 
 * License. You may obtain a copy of the License at http://www.sourcetap.com/license.htm
 * Software distributed under the License is distributed on an  "AS IS"  basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 */


import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;


/**
 *
 * @author  Administrator
 * @version
 */
public class CsvConverter {
    private static String DELIM = ",";
    private String[] headers = null;
    private ArrayList data = new ArrayList();

    public CsvConverter(Reader in) {
        String line = "";
        boolean doHeader = true;
        StringTokenizer st = null;

        try {
            BufferedReader br = new BufferedReader(in);

            while ((line = br.readLine()) != null) {
                if (line == null) {
                    throw new IOException("Empty Data Source");
                }

                if (doHeader) {
                    headers = breakCSVStringApart(line);
                    doHeader = false;
                } else {
                    String[] rowArray = breakCSVStringApart(line);

                    if ((rowArray.length < headers.length) &&
                            (rowArray.length < 2)) {
                        //skip as blank row
                    } else {
                        data.add(rowArray);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                ;
            }
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @return 
     *
     * @throws IOException 
     */
    public String[] getHeader() throws IOException {
        return headers;
    }

    /**
     * DOCUMENT ME!
     *
     * @return 
     *
     * @throws IOException 
     */
    public ArrayList getData() throws IOException {
        return data;
    }

    /**
     * DOCUMENT ME!
     *
     * @param fileName 
     */
    public void writeToFile(String fileName) {
        try {
            FileWriter bwOut = new FileWriter(fileName);

            //write headers
            for (int i = 0; i < headers.length; i++) {
                bwOut.write(createCSVField(headers[i]));

                if (i != (headers.length - 1)) {
                    bwOut.write(",");
                }
            }

            bwOut.write("\n");

            //write data
            for (int i = 0; i < data.size(); i++) {
                String[] dataArray = (String[]) data.get(i);

                for (int j = 0; j < dataArray.length; j++) {
                    bwOut.write(createCSVField(dataArray[j]));

                    if (j != (dataArray.length - 1)) {
                        bwOut.write(",");
                    }
                }

                bwOut.write("\n");
            }

            bwOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param in 
     *
     * @return 
     */
    public String[] breakCSVStringApart(String in) {
        StringBuffer curString = new StringBuffer();
        List strings = new ArrayList();
        boolean escaped = false;
        boolean inquotedstring = false;

        for (int i = 0; i < in.length(); i++) {
            char c = in.charAt(i);

            switch (c) {
            case ',':

                if (inquotedstring) {
                    curString.append(',');
                } else {
                    strings.add(curString.toString().trim());
                    curString = new StringBuffer();
                }

            case ' ':

                // end word
                //if (inquotedstring) {
                curString.append(' ');

                //}
                break;

            case '\t':

                // end word
                if (inquotedstring) {
                    curString.append('\t');
                }

                break;

            case '"':

                if (escaped) {
                    curString.append('"');
                    escaped = false;
                } else if (inquotedstring) {
                    inquotedstring = false;

                    //strings.add(curString.toString());
                    //curString = new StringBuffer();
                } else {
                    inquotedstring = true;
                }

                break;

            case '\\':

                if (escaped) {
                    curString.append("\\");
                    escaped = false;
                } else {
                    escaped = true;
                }

                break;

            default:

                if (escaped) {
                    switch (c) {
                    case 'n':
                        curString.append('\n');

                        break;

                    case 't':
                        curString.append('\t');

                        break;

                    case 'r':
                        curString.append('\r');

                        break;

                    default:
                        break;
                    }

                    escaped = false;
                } else {
                    curString.append(c);
                }
            }
        }

        if (curString.length() > 0) {
            strings.add(curString.toString().trim());
        }

        return (String[]) strings.toArray(new String[0]);
    }

    /**
     * DOCUMENT ME!
     *
     * @param in 
     *
     * @return 
     */
    public static String createCSVField(String in) {
        StringBuffer curString = new StringBuffer();
        boolean needsQuotes = false;

        for (int i = 0; i < in.length(); i++) {
            char c = in.charAt(i);

            switch (c) {
            case '\n':
                curString.append("\\n");

                break;

            case '\t':
                curString.append("\\t");

                break;

            case '\r':
                curString.append("\\r");

                break;

            case ',':
                curString.append(",");
                needsQuotes = true;

                break;

            case '\\':
                curString.append("\\\\");

                break;

            case '"':
                curString.append("\\\"");

                break;

            default:
                curString.append(c);

                break;
            }
        }

        if (needsQuotes) {
            return "\"" + curString.toString() + "\"";
        } else {
            return curString.toString();
        }
    }
}

   
    
    
    
  








Related examples in the same category

1.A utility class that parses a Comma Separated Values (CSV) file
2.Simple demo of CSV parser classSimple demo of CSV parser class
3.CSV in action: lines from a file and printCSV in action: lines from a file and print
4.Simple demo of CSV matching using Regular Expressions
5.Helper class to write table data to a csv-file (comma separated values).
6.Builds a bracketed CSV list from the array
7.Builds a CSV list from the specified String[], separator string and quote string
8.Builds a CSV list from the specified two dimensional String[][], separator string and quote string.
9.The csv tokenizer class allows an application to break a Comma Separated Value format into tokens.
10.The CSVQuoter is a helper class to encode a string for the CSV file format.
11.A stream based parser for parsing delimited text data from a file or a stream
12.Reads CSV (Comma Separated Value) files
13.Writes CSV (Comma Separated Value) files
14.CVS reader
15.CSV Writer
16.CSV parser
17.Csv Reader
18.A very simple CSV parser released under a commercial-friendly license.
19.A very simple CSV reader released under a commercial-friendly license.
20.A very simple CSV writer released under a commercial-friendly license.
21.CSV file reader
22.CSV file writer
23.CSV Tokenizer Util
24.Parse a line of text in CSV format and returns array of Strings Implementation of parsing is extracted from open-csv.
25.CSV Writer
26.Parse comma-separated list of ints and return as array
27.Parse comma-separated list of longs and return as array