`
terran_li2008
  • 浏览: 200112 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

openCSV 开源程序解析CSV文件

    博客分类:
  • java
 
阅读更多

以下内容转自:http://extjs2.iteye.com/blog/469548

 

 

读CSV

Java代码  
  1. package au.com.bytecode.opencsv;   
  2.   
  3. /**  
  4.  Copyright 2005 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.BufferedReader;   
  20. import java.io.IOException;   
  21. import java.io.Reader;   
  22. import java.util.ArrayList;   
  23. import java.util.List;   
  24.   
  25. /**  
  26.  * A very simple CSV reader released under a commercial-friendly license.  
  27.  *   
  28.  * @author Glen Smith  
  29.  *   
  30.  */  
  31. public class CSVReader {   
  32.   
  33.     private BufferedReader br;   
  34.   
  35.     private boolean hasNext = true;   
  36.   
  37.     private char separator;   
  38.   
  39.     private char quotechar;   
  40.        
  41.     private int skipLines;   
  42.   
  43.     private boolean linesSkiped;   
  44.   
  45.     /** The default separator to use if none is supplied to the constructor. */  
  46.     public static final char DEFAULT_SEPARATOR = ',';   
  47.   
  48.     /**  
  49.      * The default quote character to use if none is supplied to the  
  50.      * constructor.  
  51.      */  
  52.     public static final char DEFAULT_QUOTE_CHARACTER = '"';   
  53.        
  54.     /**  
  55.      * The default line to start reading.  
  56.      */  
  57.     public static final int DEFAULT_SKIP_LINES = 0;   
  58.   
  59.     /**  
  60.      * Constructs CSVReader using a comma for the separator.  
  61.      *   
  62.      * @param reader  
  63.      *            the reader to an underlying CSV source.  
  64.      */  
  65.     public CSVReader(Reader reader) {   
  66.         this(reader, DEFAULT_SEPARATOR);   
  67.     }   
  68.   
  69.     /**  
  70.      * Constructs CSVReader with supplied separator.  
  71.      *   
  72.      * @param reader  
  73.      *            the reader to an underlying CSV source.  
  74.      * @param separator  
  75.      *            the delimiter to use for separating entries.  
  76.      */  
  77.     public CSVReader(Reader reader, char separator) {   
  78.         this(reader, separator, DEFAULT_QUOTE_CHARACTER);   
  79.     }   
  80.        
  81.        
  82.   
  83.     /**  
  84.      * Constructs CSVReader with supplied separator and quote char.  
  85.      *   
  86.      * @param reader  
  87.      *            the reader to an underlying CSV source.  
  88.      * @param separator  
  89.      *            the delimiter to use for separating entries  
  90.      * @param quotechar  
  91.      *            the character to use for quoted elements  
  92.      */  
  93.     public CSVReader(Reader reader, char separator, char quotechar) {   
  94.         this(reader, separator, quotechar, DEFAULT_SKIP_LINES);   
  95.     }   
  96.        
  97.     /**  
  98.      * Constructs CSVReader with supplied separator and quote char.  
  99.      *   
  100.      * @param reader  
  101.      *            the reader to an underlying CSV source.  
  102.      * @param separator  
  103.      *            the delimiter to use for separating entries  
  104.      * @param quotechar  
  105.      *            the character to use for quoted elements  
  106.      * @param line  
  107.      *            the line number to skip for start reading   
  108.      */  
  109.     public CSVReader(Reader reader, char separator, char quotechar, int line) {   
  110.         this.br = new BufferedReader(reader);   
  111.         this.separator = separator;   
  112.         this.quotechar = quotechar;   
  113.         this.skipLines = line;   
  114.     }   
  115.   
  116.     /**  
  117.      * Reads the entire file into a List with each element being a String[] of  
  118.      * tokens.  
  119.      *   
  120.      * @return a List of String[], with each String[] representing a line of the  
  121.      *         file.  
  122.      *   
  123.      * @throws IOException  
  124.      *             if bad things happen during the read  
  125.      */  
  126.     public List readAll() throws IOException {   
  127.   
  128.         List allElements = new ArrayList();   
  129.         while (hasNext) {   
  130.             String[] nextLineAsTokens = readNext();   
  131.             if (nextLineAsTokens != null)   
  132.                 allElements.add(nextLineAsTokens);   
  133.         }   
  134.         return allElements;   
  135.   
  136.     }   
  137.   
  138.     /**  
  139.      * Reads the next line from the buffer and converts to a string array.  
  140.      *   
  141.      * @return a string array with each comma-separated element as a separate  
  142.      *         entry.  
  143.      *   
  144.      * @throws IOException  
  145.      *             if bad things happen during the read  
  146.      */  
  147.     public String[] readNext() throws IOException {   
  148.   
  149.         String nextLine = getNextLine();   
  150.         return hasNext ? parseLine(nextLine) : null;   
  151.     }   
  152.   
  153.     /**  
  154.      * Reads the next line from the file.  
  155.      *   
  156.      * @return the next line from the file without trailing newline  
  157.      * @throws IOException  
  158.      *             if bad things happen during the read  
  159.      */  
  160.     private String getNextLine() throws IOException {   
  161.         if (!this.linesSkiped) {   
  162.             for (int i = 0; i < skipLines; i++) {   
  163.                 br.readLine();   
  164.             }   
  165.             this.linesSkiped = true;   
  166.         }   
  167.         String nextLine = br.readLine();   
  168.         if (nextLine == null) {   
  169.             hasNext = false;   
  170.         }   
  171.         return hasNext ? nextLine : null;   
  172.     }   
  173.   
  174.     /**  
  175.      * Parses an incoming String and returns an array of elements.  
  176.      *   
  177.      * @param nextLine  
  178.      *            the string to parse  
  179.      * @return the comma-tokenized list of elements, or null if nextLine is null  
  180.      * @throws IOException if bad things happen during the read  
  181.      */  
  182.     private String[] parseLine(String nextLine) throws IOException {   
  183.   
  184.         if (nextLine == null) {   
  185.             return null;   
  186.         }   
  187.   
  188.         List tokensOnThisLine = new ArrayList();   
  189.         StringBuffer sb = new StringBuffer();   
  190.         boolean inQuotes = false;   
  191.         do {   
  192.             if (inQuotes) {   
  193.                 // continuing a quoted section, reappend newline   
  194.                 sb.append("\n");   
  195.                 nextLine = getNextLine();   
  196.                 if (nextLine == null)   
  197.                     break;   
  198.             }   
  199.             for (int i = 0; i < nextLine.length(); i++) {   
  200.   
  201.                 char c = nextLine.charAt(i);   
  202.                 if (c == quotechar) {   
  203.                     // this gets complex... the quote may end a quoted block, or escape another quote.   
  204.                     // do a 1-char lookahead:   
  205.                     if( inQuotes  // we are in quotes, therefore there can be escaped quotes in here.   
  206.                         && nextLine.length() > (i+1)  // there is indeed another character to check.   
  207.                         && nextLine.charAt(i+1) == quotechar ){ // ..and that char. is a quote also.   
  208.                         // we have two quote chars in a row == one quote char, so consume them both and   
  209.                         // put one on the token. we do *not* exit the quoted text.   
  210.                         sb.append(nextLine.charAt(i+1));   
  211.                         i++;   
  212.                     }else{   
  213.                         inQuotes = !inQuotes;   
  214.                         // the tricky case of an embedded quote in the middle: a,bc"d"ef,g   
  215.                         if(i>2 //not on the begining of the line   
  216.                                 && nextLine.charAt(i-1) != this.separator //not at the begining of an escape sequence    
  217.                                 && nextLine.length()>(i+1) &&   
  218.                                 nextLine.charAt(i+1) != this.separator //not at the end of an escape sequence   
  219.                         ){   
  220.                             sb.append(c);   
  221.                         }   
  222.                     }   
  223.                 } else if (c == separator && !inQuotes) {   
  224.                     tokensOnThisLine.add(sb.toString());   
  225.                     sb = new StringBuffer(); // start work on next token   
  226.                 } else {   
  227.                     sb.append(c);   
  228.                 }   
  229.             }   
  230.         } while (inQuotes);   
  231.         tokensOnThisLine.add(sb.toString());   
  232.         return (String[]) tokensOnThisLine.toArray(new String[0]);   
  233.   
  234.     }   
  235.   
  236.     /**  
  237.      * Closes the underlying reader.  
  238.      *   
  239.      * @throws IOException if the close fails  
  240.      */  
  241.     public void close() throws IOException{   
  242.         br.close();   
  243.     }   
  244.        
  245. }  
package au.com.bytecode.opencsv;

/**
 Copyright 2005 Bytecode Pty Ltd.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
 * A very simple CSV reader released under a commercial-friendly license.
 * 
 * @author Glen Smith
 * 
 */
public class CSVReader {

    private BufferedReader br;

    private boolean hasNext = true;

    private char separator;

    private char quotechar;
    
    private int skipLines;

    private boolean linesSkiped;

    /** The default separator to use if none is supplied to the constructor. */
    public static final char DEFAULT_SEPARATOR = ',';

    /**
     * The default quote character to use if none is supplied to the
     * constructor.
     */
    public static final char DEFAULT_QUOTE_CHARACTER = '"';
    
    /**
     * The default line to start reading.
     */
    public static final int DEFAULT_SKIP_LINES = 0;

    /**
     * Constructs CSVReader using a comma for the separator.
     * 
     * @param reader
     *            the reader to an underlying CSV source.
     */
    public CSVReader(Reader reader) {
        this(reader, DEFAULT_SEPARATOR);
    }

    /**
     * Constructs CSVReader with supplied separator.
     * 
     * @param reader
     *            the reader to an underlying CSV source.
     * @param separator
     *            the delimiter to use for separating entries.
     */
    public CSVReader(Reader reader, char separator) {
        this(reader, separator, DEFAULT_QUOTE_CHARACTER);
    }
    
    

    /**
     * Constructs CSVReader with supplied separator and quote char.
     * 
     * @param reader
     *            the reader to an underlying CSV source.
     * @param separator
     *            the delimiter to use for separating entries
     * @param quotechar
     *            the character to use for quoted elements
     */
    public CSVReader(Reader reader, char separator, char quotechar) {
        this(reader, separator, quotechar, DEFAULT_SKIP_LINES);
    }
    
    /**
     * Constructs CSVReader with supplied separator and quote char.
     * 
     * @param reader
     *            the reader to an underlying CSV source.
     * @param separator
     *            the delimiter to use for separating entries
     * @param quotechar
     *            the character to use for quoted elements
     * @param line
     *            the line number to skip for start reading 
     */
    public CSVReader(Reader reader, char separator, char quotechar, int line) {
        this.br = new BufferedReader(reader);
        this.separator = separator;
        this.quotechar = quotechar;
        this.skipLines = line;
    }

    /**
     * Reads the entire file into a List with each element being a String[] of
     * tokens.
     * 
     * @return a List of String[], with each String[] representing a line of the
     *         file.
     * 
     * @throws IOException
     *             if bad things happen during the read
     */
    public List readAll() throws IOException {

        List allElements = new ArrayList();
        while (hasNext) {
            String[] nextLineAsTokens = readNext();
            if (nextLineAsTokens != null)
                allElements.add(nextLineAsTokens);
        }
        return allElements;

    }

    /**
     * Reads the next line from the buffer and converts to a string array.
     * 
     * @return a string array with each comma-separated element as a separate
     *         entry.
     * 
     * @throws IOException
     *             if bad things happen during the read
     */
    public String[] readNext() throws IOException {

        String nextLine = getNextLine();
        return hasNext ? parseLine(nextLine) : null;
    }

    /**
     * Reads the next line from the file.
     * 
     * @return the next line from the file without trailing newline
     * @throws IOException
     *             if bad things happen during the read
     */
    private String getNextLine() throws IOException {
    	if (!this.linesSkiped) {
            for (int i = 0; i < skipLines; i++) {
                br.readLine();
            }
            this.linesSkiped = true;
        }
        String nextLine = br.readLine();
        if (nextLine == null) {
            hasNext = false;
        }
        return hasNext ? nextLine : null;
    }

    /**
     * Parses an incoming String and returns an array of elements.
     * 
     * @param nextLine
     *            the string to parse
     * @return the comma-tokenized list of elements, or null if nextLine is null
     * @throws IOException if bad things happen during the read
     */
    private String[] parseLine(String nextLine) throws IOException {

        if (nextLine == null) {
            return null;
        }

        List tokensOnThisLine = new ArrayList();
        StringBuffer sb = new StringBuffer();
        boolean inQuotes = false;
        do {
        	if (inQuotes) {
                // continuing a quoted section, reappend newline
                sb.append("\n");
                nextLine = getNextLine();
                if (nextLine == null)
                    break;
            }
            for (int i = 0; i < nextLine.length(); i++) {

                char c = nextLine.charAt(i);
                if (c == quotechar) {
                	// this gets complex... the quote may end a quoted block, or escape another quote.
                	// do a 1-char lookahead:
                	if( inQuotes  // we are in quotes, therefore there can be escaped quotes in here.
                	    && nextLine.length() > (i+1)  // there is indeed another character to check.
                	    && nextLine.charAt(i+1) == quotechar ){ // ..and that char. is a quote also.
                		// we have two quote chars in a row == one quote char, so consume them both and
                		// put one on the token. we do *not* exit the quoted text.
                		sb.append(nextLine.charAt(i+1));
                		i++;
                	}else{
                		inQuotes = !inQuotes;
                		// the tricky case of an embedded quote in the middle: a,bc"d"ef,g
                		if(i>2 //not on the begining of the line
                				&& nextLine.charAt(i-1) != this.separator //not at the begining of an escape sequence 
                				&& nextLine.length()>(i+1) &&
                				nextLine.charAt(i+1) != this.separator //not at the	end of an escape sequence
                		){
                			sb.append(c);
                		}
                	}
                } else if (c == separator && !inQuotes) {
                    tokensOnThisLine.add(sb.toString());
                    sb = new StringBuffer(); // start work on next token
                } else {
                    sb.append(c);
                }
            }
        } while (inQuotes);
        tokensOnThisLine.add(sb.toString());
        return (String[]) tokensOnThisLine.toArray(new String[0]);

    }

    /**
     * Closes the underlying reader.
     * 
     * @throws IOException if the close fails
     */
    public void close() throws IOException{
    	br.close();
    }
    
}




写CSV
Java代码 复制代码 收藏代码
  1. package au.com.bytecode.opencsv;   
  2.   
  3. /**  
  4.  Copyright 2005 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.PrintWriter;   
  21. import java.io.Reader;   
  22. import java.io.Writer;   
  23. import java.sql.Clob;   
  24. import java.sql.ResultSet;   
  25. import java.sql.ResultSetMetaData;   
  26. import java.sql.SQLException;   
  27. import java.sql.Time;   
  28. import java.sql.Timestamp;   
  29. import java.sql.Types;   
  30. import java.util.Iterator;   
  31. import java.util.List;   
  32.   
  33. /**  
  34.  * A very simple CSV writer released under a commercial-friendly license.  
  35.  *  
  36.  * @author Glen Smith  
  37.  *  
  38.  */  
  39. public class CSVWriter {   
  40.        
  41.     private Writer rawWriter;   
  42.   
  43.     private PrintWriter pw;   
  44.   
  45.     private char separator;   
  46.   
  47.     private char quotechar;   
  48.        
  49.     private String lineEnd;   
  50.   
  51.     /** The character used for escaping quotes. */  
  52.     public static final char ESCAPE_CHARACTER = '"';   
  53.   
  54.     /** The default separator to use if none is supplied to the constructor. */  
  55.     public static final char DEFAULT_SEPARATOR = ',';   
  56.   
  57.     /**  
  58.      * The default quote character to use if none is supplied to the  
  59.      * constructor.  
  60.      */  
  61.     public static final char DEFAULT_QUOTE_CHARACTER = '"';   
  62.        
  63.     /** The quote constant to use when you wish to suppress all quoting. */  
  64.     public static final char NO_QUOTE_CHARACTER = '\u0000';   
  65.        
  66.     /** Default line terminator uses platform encoding. */  
  67.     public static final String DEFAULT_LINE_END = "\n";   
  68.   
  69.     /**  
  70.      * Constructs CSVWriter using a comma for the separator.  
  71.      *  
  72.      * @param writer  
  73.      *            the writer to an underlying CSV source.  
  74.      */  
  75.     public CSVWriter(Writer writer) {   
  76.         this(writer, DEFAULT_SEPARATOR);   
  77.     }   
  78.   
  79.     /**  
  80.      * Constructs CSVWriter with supplied separator.  
  81.      *  
  82.      * @param writer  
  83.      *            the writer to an underlying CSV source.  
  84.      * @param separator  
  85.      *            the delimiter to use for separating entries.  
  86.      */  
  87.     public CSVWriter(Writer writer, char separator) {   
  88.         this(writer, separator, DEFAULT_QUOTE_CHARACTER);   
  89.     }   
  90.   
  91.     /**  
  92.      * Constructs CSVWriter with supplied separator and quote char.  
  93.      *  
  94.      * @param writer  
  95.      *            the writer to an underlying CSV source.  
  96.      * @param separator  
  97.      *            the delimiter to use for separating entries  
  98.      * @param quotechar  
  99.      *            the character to use for quoted elements  
  100.      */  
  101.     public CSVWriter(Writer writer, char separator, char quotechar) {   
  102.         this(writer, separator, quotechar, "\n");   
  103.     }   
  104.   
  105.     /**  
  106.      * Constructs CSVWriter with supplied separator and quote char.  
  107.      *  
  108.      * @param writer  
  109.      *            the writer to an underlying CSV source.  
  110.      * @param separator  
  111.      *            the delimiter to use for separating entries  
  112.      * @param quotechar  
  113.      *            the character to use for quoted elements  
  114.      * @param lineEnd  
  115.      *            the line feed terminator to use  
  116.      */  
  117.     public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) {   
  118.         this.rawWriter = writer;   
  119.         this.pw = new PrintWriter(writer);   
  120.         this.separator = separator;   
  121.         this.quotechar = quotechar;   
  122.         this.lineEnd = lineEnd;   
  123.     }   
  124.        
  125.     /**  
  126.      * Writes the entire list to a CSV file. The list is assumed to be a  
  127.      * String[]  
  128.      *  
  129.      * @param allLines  
  130.      *            a List of String[], with each String[] representing a line of  
  131.      *            the file.  
  132.      */  
  133.     public void writeAll(List allLines)  {   
  134.   
  135.         for (Iterator iter = allLines.iterator(); iter.hasNext();) {   
  136.             String[] nextLine = (String[]) iter.next();   
  137.             writeNext(nextLine);   
  138.         }   
  139.   
  140.     }   
  141.   
  142.     protected void writeColumnNames(ResultSetMetaData metadata)   
  143.         throws SQLException {   
  144.            
  145.         int columnCount =  metadata.getColumnCount();   
  146.            
  147.         String[] nextLine = new String[columnCount];   
  148.         for (int i = 0; i < columnCount; i++) {   
  149.             nextLine[i] = metadata.getColumnName(i + 1);   
  150.         }   
  151.         writeNext(nextLine);   
  152.     }   
  153.        
  154.     /**  
  155.      * Writes the entire ResultSet to a CSV file.  
  156.      *  
  157.      * The caller is responsible for closing the ResultSet.  
  158.      *  
  159.      * @param rs the recordset to write  
  160.      * @param includeColumnNames true if you want column names in the output, false otherwise  
  161.      *  
  162.      */  
  163.     public void writeAll(java.sql.ResultSet rs, boolean includeColumnNames)  throws SQLException, IOException {   
  164.            
  165.         ResultSetMetaData metadata = rs.getMetaData();   
  166.            
  167.            
  168.         if (includeColumnNames) {   
  169.             writeColumnNames(metadata);   
  170.         }   
  171.   
  172.         int columnCount =  metadata.getColumnCount();   
  173.            
  174.         while (rs.next())   
  175.         {   
  176.             String[] nextLine = new String[columnCount];   
  177.                
  178.             for (int i = 0; i < columnCount; i++) {   
  179.                 nextLine[i] = getColumnValue(rs, metadata.getColumnType(i + 1), i + 1);   
  180.             }   
  181.                
  182.             writeNext(nextLine);   
  183.         }   
  184.     }   
  185.        
  186.     private static String getColumnValue(ResultSet rs, int colType, int colIndex)   
  187.             throws SQLException, IOException {   
  188.   
  189.         String value = "";   
  190.            
  191.         switch (colType)   
  192.         {   
  193.             case Types.BIT:   
  194.                 Object bit = rs.getObject(colIndex);   
  195.                 value = String.valueOf(bit);   
  196.             break;   
  197.             case Types.BOOLEAN:   
  198.                 boolean b = rs.getBoolean(colIndex);   
  199.                 if (!rs.wasNull()) {   
  200.                 value = Boolean.valueOf(b).toString();   
  201.             }   
  202.             break;   
  203.             case Types.CLOB:   
  204.                 value = read(rs.getClob(colIndex));   
  205.             break;   
  206.             case Types.BIGINT:   
  207.             case Types.DECIMAL:   
  208.             case Types.DOUBLE:   
  209.             case Types.FLOAT:   
  210.             case Types.REAL:   
  211.             case Types.NUMERIC:   
  212.                 value = "" + rs.getBigDecimal(colIndex).doubleValue();   
  213.             break;   
  214.             case Types.INTEGER:   
  215.             case Types.TINYINT:   
  216.             case Types.SMALLINT:   
  217.                 int intValue = rs.getInt(colIndex);   
  218.                 if (!rs.wasNull()) {   
  219.                     value = "" + intValue;   
  220.                 }   
  221.             break;   
  222.             case Types.JAVA_OBJECT:   
  223.                 Object obj = rs.getObject(colIndex);   
  224.                 if (obj != null) {   
  225.                     value = String.valueOf(obj);   
  226.                 }   
  227.             break;   
  228.             case Types.DATE:   
  229.                 value = rs.getDate(colIndex).toString();   
  230.             break;   
  231.             case Types.TIME:   
  232.                 Time t = rs.getTime(colIndex);   
  233.                 value = t.toString();   
  234.             break;   
  235.             case Types.TIMESTAMP:   
  236.                 Timestamp tstamp = rs.getTimestamp(colIndex);   
  237.                 value = tstamp.toString();   
  238.             break;   
  239.             case Types.LONGVARCHAR:   
  240.             case Types.VARCHAR:   
  241.             case Types.CHAR:   
  242.                 value = rs.getString(colIndex);   
  243.             break;   
  244.             default:   
  245.                 value = "";   
  246.         }   
  247.   
  248.         return value;   
  249.            
  250.     }   
  251.   
  252.     private static String read(Clob c) throws SQLException, IOException   
  253.     {   
  254.         StringBuffer sb = new StringBuffer( (int) c.length());   
  255.         Reader r = c.getCharacterStream();   
  256.         char[] cbuf = new char[2048];   
  257.         int n = 0;   
  258.         while ((n = r.read(cbuf, 0, cbuf.length)) != -1) {   
  259.             if (n > 0) {   
  260.                 sb.append(cbuf, 0, n);   
  261.             }   
  262.         }   
  263.         return sb.toString();   
  264.     }   
  265.        
  266.     /**  
  267.      * Writes the next line to the file.  
  268.      *  
  269.      * @param nextLine  
  270.      *            a string array with each comma-separated element as a separate  
  271.      *            entry.  
  272.      */  
  273.     public void writeNext(String[] nextLine) {   
  274.         StringBuffer sb = new StringBuffer();   
  275.         for (int i = 0; i < nextLine.length; i++) {   
  276.   
  277.             if (i != 0) {   
  278.                 sb.append(separator);   
  279.             }   
  280.   
  281.             String nextElement = nextLine[i];   
  282.             if (nextElement == null)   
  283.                 continue;   
  284.             if (quotechar !=  NO_QUOTE_CHARACTER)   
  285.                 sb.append(quotechar);   
  286.             for (int j = 0; j < nextElement.length(); j++) {   
  287.                 char nextChar = nextElement.charAt(j);   
  288.                 if (nextChar == quotechar) {   
  289.                     sb.append(ESCAPE_CHARACTER).append(nextChar);   
  290.                 } else if (nextChar == ESCAPE_CHARACTER) {   
  291.                     sb.append(ESCAPE_CHARACTER).append(nextChar);   
  292.                 } else {   
  293.                     sb.append(nextChar);   
  294.                 }   
  295.             }   
  296.             if (quotechar != NO_QUOTE_CHARACTER)   
  297.                 sb.append(quotechar);   
  298.         }   
  299.            
  300.         sb.append(lineEnd);   
  301.         pw.write(sb.toString());   
  302.   
  303.     }   
  304.   
  305.     /**  
  306.      * Close the underlying stream writer flushing any buffered content.  
  307.      *  
  308.      * @throws IOException if bad things happen  
  309.      *  
  310.      */  
  311.     public void close() throws IOException {   
  312.         pw.flush();   
  313.         pw.close();   
  314.         rawWriter.close();   
  315.     }   
  316.   
  317. }  

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics