001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     * 
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     * 
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.commons.csv;
018    
019    import java.io.StringWriter;
020    import java.io.StringReader;
021    import java.io.IOException;
022    
023    /**
024     * Utility methods for dealing with CSV files
025     */
026    public class CSVUtils {
027    
028        private static final String[] EMPTY_STRING_ARRAY = new String[0];
029        private static final String[][] EMPTY_DOUBLE_STRING_ARRAY = new String[0][0];
030    
031        /**
032         * <p><code>CSVUtils</code> instances should NOT be constructed in
033         * standard programming.
034         *
035         * <p>This constructor is public to permit tools that require a JavaBean
036         * instance to operate.</p>
037         */
038        public CSVUtils() {
039        }
040    
041        /**
042         * Converts an array of string values into a single CSV line. All
043         * <code>null</code> values are converted to the string <code>"null"</code>,
044         * all strings equal to <code>"null"</code> will additionally get quotes
045         * around.
046         *
047         * @param values the value array
048         * @return the CSV string, will be an empty string if the length of the
049         *         value array is 0
050         */
051        public static String printLine(String[] values, CSVStrategy strategy) {
052            // set up a CSVUtils
053            StringWriter stringWriter = new StringWriter();
054            CSVPrinter csvPrinter = new CSVPrinter(stringWriter, strategy);
055    
056            // check for null values an "null" as strings and convert them
057            // into the strings "null" and "\"null\""
058            for (int i = 0; i < values.length; i++) {
059                if (values[i] == null) {
060                    values[i] = "null";
061                } else if (values[i].equals("null")) {
062                    values[i] = "\"null\"";
063                }
064            }
065    
066            // convert to CSV
067            try {
068                csvPrinter.println(values);
069            } catch (IOException e) {
070                // should not happen with StringWriter
071            }
072            // as the resulting string has \r\n at the end, we will trim that away
073            return stringWriter.toString().trim();
074        }
075    
076        // ======================================================
077        //  static parsers
078        // ======================================================
079    
080        /**
081         * Parses the given String according to the default {@link CSVStrategy}.
082         *
083         * @param s CSV String to be parsed.
084         * @return parsed String matrix (which is never null)
085         * @throws IOException in case of error
086         */
087        public static String[][] parse(String s) throws IOException {
088            if (s == null) {
089                throw new IllegalArgumentException("Null argument not allowed.");
090            }
091            String[][] result = (new CSVParser(new StringReader(s))).getAllValues();
092            if (result == null) {
093                // since CSVStrategy ignores empty lines an empty array is returned
094                // (i.e. not "result = new String[][] {{""}};")
095                result = EMPTY_DOUBLE_STRING_ARRAY;
096            }
097            return result;
098        }
099    
100        /**
101         * Parses the first line only according to the default {@link CSVStrategy}.
102         *
103         * Parsing empty string will be handled as valid records containing zero
104         * elements, so the following property holds: parseLine("").length == 0.
105         *
106         * @param s CSV String to be parsed.
107         * @return parsed String vector (which is never null)
108         * @throws IOException in case of error
109         */
110        public static String[] parseLine(String s) throws IOException {
111            if (s == null) {
112                throw new IllegalArgumentException("Null argument not allowed.");
113            }
114            // uh,jh: make sure that parseLine("").length == 0
115            if (s.length() == 0) {
116                return EMPTY_STRING_ARRAY;
117            }
118            return (new CSVParser(new StringReader(s))).getLine();
119        }
120    
121    }