CSVWriter.java
package ac.essex.ooechs.imaging.commons.util;
import java.io.File;
import java.io.IOException;
/**
* <p/>
* 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,
* provided that any use properly credits the author.
* 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 at http://www.gnu.org
* </p>
*
* @author Olly Oechsle, University of Essex, Date: 19-Nov-2007
* @version 1.0
*/
public class CSVWriter {
protected StringBuffer buffer;
private boolean first;
private boolean emptyLine = true;
public CSVWriter() {
this(null);
}
public CSVWriter(String header) {
buffer = new StringBuffer();
if (header != null) {
buffer.append(header);
buffer.append("\n");
}
first = true;
}
public void addData(double data) {
addData(String.valueOf(data));
}
public void addData(int data) {
addData(String.valueOf(data));
}
public void addData(String data) {
if (!first) buffer.append(",");
buffer.append(data);
emptyLine = false;
first = false;
}
public void addData(double[] data) {
for (int i = 0; i < data.length; i++) {
addData(data[i]);
}
}
public void addData(float[] data) {
for (int i = 0; i < data.length; i++) {
addData(data[i]);
}
}
public void addData(String[] data) {
for (int i = 0; i < data.length; i++) {
addData(data[i]);
}
}
public void addData(int[] data) {
for (int i = 0; i < data.length; i++) {
addData(data[i]);
}
}
public void newLine() {
first = true;
buffer.append("\n");
emptyLine = true;
}
public void newCommentLine() {
if (!emptyLine) {
newLine();
}
buffer.append("#");
}
public String toString() {
return buffer.toString();
}
public void save(File f) throws IOException {
FileIO.saveToFile(toString(), f);
}
}