View Javadoc
1   package com.opencsv;
2   
3   /*
4    Copyright 2018 Bytecode Pty Ltd.
5   
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9   
10   http://www.apache.org/licenses/LICENSE-2.0
11  
12   Unless required by applicable law or agreed to in writing, software
13   distributed under the License is distributed on an "AS IS" BASIS,
14   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   See the License for the specific language governing permissions and
16   limitations under the License.
17   */
18  
19  import java.io.IOException;
20  import java.io.Writer;
21  
22  /**
23   * The CSVParserWriter is a replacement for the CSVWriter that allows you to pass in a ICSVParser
24   * to handle the task of converting a string array to a line of CSV data.  This way you have the same class
25   * creating the data as reading it.
26   *
27   * @author Scott Conway
28   * @since 4.2
29   */
30  public class CSVParserWriter extends AbstractCSVWriter {
31      protected final ICSVParser parser;
32  
33      /**
34       * Constructor for the CSVParserWriter.
35       *
36       * @param writer  - The writer to an underlying CSV source.
37       * @param parser  - ICSVParser to convert the String array to csv formatted string.
38       * @param lineEnd - Desired line end String (either "\n" or "\r\n").
39       */
40      public CSVParserWriter(Writer writer, ICSVParser parser, String lineEnd) {
41          super(writer, lineEnd);
42          this.parser = parser;
43      }
44  
45      @Override
46      protected void writeNext(String[] nextLine, boolean applyQuotesToAll, Appendable appendable) throws IOException {
47          parser.parseToLine(nextLine, applyQuotesToAll, appendable);
48          appendable.append(getLineEnd());
49          getWriter().write(appendable.toString());
50      }
51  }