- 浏览: 2166235 次
- 性别:
- 来自: 北京
-
文章分类
最新评论
-
sunzeshan:
找了很久,用了这个插件解决问题啦。谢谢
eclipse jetty debug source not found -
xiaosong0112:
您好,请问为什么要这样设置呢,原理是什么?在网上很多转帖都没有 ...
maven的jetty插件提示No Transaction manager found导致启动慢的解决方法 -
eimhee:
tjzx 写道畅搜谷歌:http://dian168.cc/打 ...
Google 镜像站搜集 -
tjzx:
畅搜谷歌:http://dian168.cc/打开的是“最火源 ...
Google 镜像站搜集 -
eimhee:
finallygo 写道你这属于"头痛医头脚痛医脚& ...
解决linux下too many file问题
读CSV
写CSV
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
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.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.sql.Clob; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Iterator; import java.util.List; /** * A very simple CSV writer released under a commercial-friendly license. * * @author Glen Smith * */ public class CSVWriter { private Writer rawWriter; private PrintWriter pw; private char separator; private char quotechar; private String lineEnd; /** The character used for escaping quotes. */ public static final char ESCAPE_CHARACTER = '"'; /** 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 quote constant to use when you wish to suppress all quoting. */ public static final char NO_QUOTE_CHARACTER = '\u0000'; /** Default line terminator uses platform encoding. */ public static final String DEFAULT_LINE_END = "\n"; /** * Constructs CSVWriter using a comma for the separator. * * @param writer * the writer to an underlying CSV source. */ public CSVWriter(Writer writer) { this(writer, DEFAULT_SEPARATOR); } /** * Constructs CSVWriter with supplied separator. * * @param writer * the writer to an underlying CSV source. * @param separator * the delimiter to use for separating entries. */ public CSVWriter(Writer writer, char separator) { this(writer, separator, DEFAULT_QUOTE_CHARACTER); } /** * Constructs CSVWriter with supplied separator and quote char. * * @param writer * the writer to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements */ public CSVWriter(Writer writer, char separator, char quotechar) { this(writer, separator, quotechar, "\n"); } /** * Constructs CSVWriter with supplied separator and quote char. * * @param writer * the writer to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param lineEnd * the line feed terminator to use */ public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) { this.rawWriter = writer; this.pw = new PrintWriter(writer); this.separator = separator; this.quotechar = quotechar; this.lineEnd = lineEnd; } /** * Writes the entire list to a CSV file. The list is assumed to be a * String[] * * @param allLines * a List of String[], with each String[] representing a line of * the file. */ public void writeAll(List allLines) { for (Iterator iter = allLines.iterator(); iter.hasNext();) { String[] nextLine = (String[]) iter.next(); writeNext(nextLine); } } protected void writeColumnNames(ResultSetMetaData metadata) throws SQLException { int columnCount = metadata.getColumnCount(); String[] nextLine = new String[columnCount]; for (int i = 0; i < columnCount; i++) { nextLine[i] = metadata.getColumnName(i + 1); } writeNext(nextLine); } /** * Writes the entire ResultSet to a CSV file. * * The caller is responsible for closing the ResultSet. * * @param rs the recordset to write * @param includeColumnNames true if you want column names in the output, false otherwise * */ public void writeAll(java.sql.ResultSet rs, boolean includeColumnNames) throws SQLException, IOException { ResultSetMetaData metadata = rs.getMetaData(); if (includeColumnNames) { writeColumnNames(metadata); } int columnCount = metadata.getColumnCount(); while (rs.next()) { String[] nextLine = new String[columnCount]; for (int i = 0; i < columnCount; i++) { nextLine[i] = getColumnValue(rs, metadata.getColumnType(i + 1), i + 1); } writeNext(nextLine); } } private static String getColumnValue(ResultSet rs, int colType, int colIndex) throws SQLException, IOException { String value = ""; switch (colType) { case Types.BIT: Object bit = rs.getObject(colIndex); value = String.valueOf(bit); break; case Types.BOOLEAN: boolean b = rs.getBoolean(colIndex); if (!rs.wasNull()) { value = Boolean.valueOf(b).toString(); } break; case Types.CLOB: value = read(rs.getClob(colIndex)); break; case Types.BIGINT: case Types.DECIMAL: case Types.DOUBLE: case Types.FLOAT: case Types.REAL: case Types.NUMERIC: value = "" + rs.getBigDecimal(colIndex).doubleValue(); break; case Types.INTEGER: case Types.TINYINT: case Types.SMALLINT: int intValue = rs.getInt(colIndex); if (!rs.wasNull()) { value = "" + intValue; } break; case Types.JAVA_OBJECT: Object obj = rs.getObject(colIndex); if (obj != null) { value = String.valueOf(obj); } break; case Types.DATE: value = rs.getDate(colIndex).toString(); break; case Types.TIME: Time t = rs.getTime(colIndex); value = t.toString(); break; case Types.TIMESTAMP: Timestamp tstamp = rs.getTimestamp(colIndex); value = tstamp.toString(); break; case Types.LONGVARCHAR: case Types.VARCHAR: case Types.CHAR: value = rs.getString(colIndex); break; default: value = ""; } return value; } private static String read(Clob c) throws SQLException, IOException { StringBuffer sb = new StringBuffer( (int) c.length()); Reader r = c.getCharacterStream(); char[] cbuf = new char[2048]; int n = 0; while ((n = r.read(cbuf, 0, cbuf.length)) != -1) { if (n > 0) { sb.append(cbuf, 0, n); } } return sb.toString(); } /** * Writes the next line to the file. * * @param nextLine * a string array with each comma-separated element as a separate * entry. */ public void writeNext(String[] nextLine) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < nextLine.length; i++) { if (i != 0) { sb.append(separator); } String nextElement = nextLine[i]; if (nextElement == null) continue; if (quotechar != NO_QUOTE_CHARACTER) sb.append(quotechar); for (int j = 0; j < nextElement.length(); j++) { char nextChar = nextElement.charAt(j); if (nextChar == quotechar) { sb.append(ESCAPE_CHARACTER).append(nextChar); } else if (nextChar == ESCAPE_CHARACTER) { sb.append(ESCAPE_CHARACTER).append(nextChar); } else { sb.append(nextChar); } } if (quotechar != NO_QUOTE_CHARACTER) sb.append(quotechar); } sb.append(lineEnd); pw.write(sb.toString()); } /** * Close the underlying stream writer flushing any buffered content. * * @throws IOException if bad things happen * */ public void close() throws IOException { pw.flush(); pw.close(); rawWriter.close(); } }
相关推荐
对于CSV文件,Java标准库没有内置的支持,但我们可以使用开源库如OpenCSV或Apache Commons CSV。解析CSV的基本步骤如下: 1. 创建CSVReader,传入文件流或文件路径。 2. 使用`readNext()`方法逐行读取CSV数据。 3. ...
首先,我们需要了解OpenCSV,这是一个开源的C#库,专门用于读写CSV文件。它提供了简单易用的API,使得在C#项目中处理CSV文件变得轻松。在NuGet包管理器中,可以搜索并安装"OpenCSV"库,将其添加到你的项目中。 转换...
了解如何有效地读取和解析CSV文件是每个Java开发者必备的技能之一,这将有助于你在处理大量数据时更加游刃有余。在使用过程中如果遇到任何问题,不要犹豫,大胆提问,社区的力量会帮你找到答案。
OpenCSV作为Java中解析CSV文件的利器,以其易用性和灵活性深受开发者喜爱。无论是简单的数据处理还是复杂的数据映射,都能游刃有余。通过上述步骤,你已经掌握了OpenCSV的基本使用,可以根据实际需求进行更深入的...
读取CSV文件通常涉及解析文件内容并将其转换为结构化数据,例如数组或对象。在Python中,我们可以使用内置的`csv`模块来完成这个任务。以下是一个简单的示例: ```python import csv with open('example.csv', 'r'...
以上就是使用Java和OpenCSV库解析CSV文件并将数据加载到数据库的基本步骤。在实际应用中,你可能需要处理更多细节,如错误处理、数据类型转换、空值处理等。此外,如果你的CSV文件非常大,可能需要考虑分块读取和...
opencsv提供了一个简单易用且高效的API,使得在Java应用程序中处理CSV文件变得轻而易举。 ### CSV格式简介 CSV文件由一系列行组成,每行包含一个或多个数据字段,字段之间用逗号分隔。在某些情况下,如果字段内包含...
OpenCSV 是一个开源的 Java 库,专门用于处理 CSV(Comma Separated Values)格式的数据。它为开发者提供了一种简单、高效的接口,使得生成和读取 CSV 文件变得非常方便。在Java开发中,处理CSV数据时,OpenCSV是一...
OpenCSV的核心功能是读取和写入CSV文件,它提供了一套简洁的API,使得开发者能够轻松地解析和生成CSV数据。下面我们将深入探讨OpenCSV 2.0的主要特性、使用方法以及与CSV文件交互的关键知识点。 1. **基本概念与...
1. **读取CSV文件**:`javacsv`提供了一种简单的方法来读取CSV文件,通过`CSVReader`类,你可以逐行读取并解析文件内容。它可以处理行结束符的差异,并允许自定义字段分隔符。 2. **写入CSV文件**:与读取相对应,`...
当涉及到在Java应用程序中读取、写入或操作CSV文件时,`javacsv.jar`库提供了强大的支持。 `javacsv.jar`是开源项目,由Dave Newton创建,它提供了一组方便的类和方法,帮助开发者轻松地与CSV数据交互。这个库已经...
解析csv文件的开源工具,十分方便好用。
`csvreader`是为MATLAB设计的一个强大的CSV解析函数,它能有效地帮助用户读取和处理CSV文件中的数据。在这个名为"matlab开发-csvreader"的压缩包中,包含了一些关键组件和文档,旨在简化CSV文件的读取操作。 首先,...
OpenCSV,一个强大的开源Java库,为我们提供了方便、高效的CSV解析和生成功能。本文将详细探讨OpenCSV 1.8版本的功能特性、使用方法以及其在实际项目中的应用。 OpenCSV是Java社区中的一款明星工具,它的主要目标是...
以Apache Commons CSV为例,我们可以创建一个`CSVParser`实例,解析CSV文件,然后遍历`CSVRecord`对象来获取每一行的数据。 对于"java-csv-reader"项目,其核心功能可能是将CSV数据转换为SQL更新查询。这涉及到解析...
2. **Java**:作为广泛使用的编程语言,Java提供了许多库来处理CSV文件,如OpenCSV、Apache Commons CSV或Java 8内置的`java.nio.file.Files`和`java.util.Scanner`。在这个项目中,你可能需要使用这些库来读取CSV...
在Java编程中,处理CSV文件通常会用到如OpenCSV、Apache Commons CSV或Java 8内置的java.nio.file.Files和java.util.Scanner类等库。开发者可能会定义一个数据模型类,对应CSV文件中的每一行,然后使用这些库将CSV...
"Excel列表转化成java对象"的主题就聚焦于这个过程,它涉及到Java对Excel和CSV文件的解析以及数据映射到Java对象的技术。 首先,我们要了解如何在Java中处理Excel文件。Java提供了多种库来处理Excel,如Apache POI...
例如,`CSVUtil.java`可能就是这样一个工具类,用于读取和解析CSV文件中的数据。这个工具类可能包含以下功能:打开文件、逐行读取、分割数据、并将其转换为可操作的结构,如二维数组或List。 接着,"皮尔逊相关性...
这里我们关注的是"CsvUtils工具",它可能是某个开源项目或个人开发的针对CSV文件操作的实用工具类。 博客链接中的文章《CsvUtils工具详解》提供了关于这个工具的详细信息。虽然具体内容未直接给出,但我们可以根据...