2
* Licensed to the Apache Software Foundation (ASF) under one
3
* or more contributor license agreements. See the NOTICE file
4
* distributed with this work for additional information
5
* regarding copyright ownership. The ASF licenses this file
6
* to you under the Apache License, Version 2.0 (the
7
* "License"); you may not use this file except in compliance
8
* with the License. You may obtain a copy of the License at
10
* http://www.apache.org/licenses/LICENSE-2.0
12
* Unless required by applicable law or agreed to in writing,
13
* software distributed under the License is distributed on an
14
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
* KIND, either express or implied. See the License for the
16
* specific language governing permissions and limitations
19
package org.apache.commons.csv.writer;
21
import java.io.Writer;
22
import java.util.Arrays;
29
* @author Martin van den Bemt
32
public class CSVWriter {
34
/** The CSV config **/
35
private CSVConfig config;
37
private Writer writer;
44
public CSVWriter(CSVConfig config) {
48
public void writeRecord(Map map) {
49
CSVField[] fields = config.getFields();
51
StringBuffer sb = new StringBuffer();
52
for (int i = 0; i < fields.length; i++) {
53
String value = (String) map.get(fields[i].getName());
54
value = writeValue(fields[i], value);
56
if (!config.isDelimiterIgnored() && fields.length != (i+1)) {
57
sb.append(config.getDelimiter());
60
if (config.isEndTrimmed()) {
61
for (int i = sb.length()-1; i >= 0; i--) {
62
System.out.println("i : " + i);
63
if (Character.isWhitespace(sb.charAt(i))) {
71
String line = sb.toString();
73
} catch(Exception e) {
78
protected String writeValue(CSVField field, String value) throws Exception {
79
if (config.isFixedWidth()) {
80
if (value.length() < field.getSize()) {
81
int fillPattern = config.getFill();
82
if (field.overrideFill()) {
83
fillPattern = field.getFill();
85
StringBuffer sb = new StringBuffer();
86
int fillSize = (field.getSize() - value.length());
87
char[] fill = new char[fillSize];
88
Arrays.fill(fill, config.getFillChar());
89
if (fillPattern == CSVConfig.FILLLEFT) {
92
value = sb.toString();
94
// defaults to fillpattern FILLRIGHT when fixedwidth is used
97
value = sb.toString();
99
} else if (value.length() > field.getSize()) {
101
value = value.substring(0, field.getSize());
103
if (!config.isValueDelimiterIgnored()) {
104
// add the value delimiter..
105
value = config.getValueDelimiter()+value+config.getValueDelimiter();
111
* @return the CVSConfig or null if not present
113
public CSVConfig getConfig() {
119
* @param config the CVSConfig
121
public void setConfig(CSVConfig config) {
122
this.config = config;
126
* Set the writer to write the CSV file to.
127
* @param writer the writer.
129
public void setWriter(Writer writer) {
130
this.writer = writer;