Mega Code Archive

 
Categories / Java / Development Class
 

CSV Writer

/* PearReview - The peer review assistant. Copyright (C) 2009  Dimitrij Pankratz, Anton Musichin http://www.pearreview.com, info@pearreview.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.  */ //package com.pearreview.util.csv; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Serializable; public class CSVWriter implements Serializable {   private static final long serialVersionUID = 2444199148253681816L;   public static final char COMMA_SEPARATOR = 0x2C;   public static final char COLON_SEPARATOR = 0x3A;   public static final char SEMICOLON_SEPARATOR = 0x3B;   public static final char TABULATOR_SEPARATOR = 0x09;   /**    * Writes a table model to csv formatted file    *     * @param file    *            file to create    * @param model    *            model to write    * @throws IOException    */   public void write(File file, CSVTableModel model, char separator)       throws IOException {     /* create file */     FileWriter fw = new FileWriter(file);     BufferedWriter bw = new BufferedWriter(fw);     String value;     /* write columns */     if (model.areColumnsVisible()) {       for (int column = 0; column < model.getColumnCount(); column++) {         value = encodeValue(model.getColumnName(column), separator);         bw.write(value);         if (column < model.getColumnCount() - 1) {           bw.write(separator);         } else {           bw.newLine();         }       }     }     /* write data */     for (int row = 0; row < model.getRowCount(); row++) {       for (int column = 0; column < model.getColumnCount(); column++) {         value = encodeValue(model.getValueAt(row, column), separator);         bw.write(value);         if (column < model.getColumnCount() - 1) {           bw.write(separator);         } else {           bw.newLine();         }       }     }     /* close file */     bw.close();   }   protected String encodeValue(String value, char separator) {     return "\"" + value + "\"";   } } interface CSVTableModel {   public String getValueAt(int row, int column);   public int getColumnCount();   public int getRowCount();   public String getColumnName(int column);   public boolean areColumnsVisible(); }