×

java读取cvs文件

java读取cvs文件(java读csv文件最好的方法)

admin admin 发表于2023-03-26 21:32:09 浏览53 评论0

抢沙发发表评论

本文目录一览:

java读取csv文件

import java.io.BufferedReader;  

import java.io.FileReader;  

import java.util.*;

public class Test{

    public static void main(String[] args) {

        HashtableString, String[] dict = new HashtableString, String[]();

        try {  

            BufferedReader reader = new BufferedReader(new FileReader("test.csv"));

            String line = null;  

            while((line=reader.readLine())!=null){  

                String item[] = line.split(",");

                String item2[] = new String[19];

                System.arraycopy(item,1,item2,0,19);

                dict.put(item[0],item2);

            }  

            Enumeration e2 = dict.keys();

            while (e2.hasMoreElements()) {

                String key = (String) e2.nextElement();

                System.out.println(key);

                String[] dd = (String[])dict.get(key);

                for (int i=0;idd.length;i++) {

                    System.out.print(dd[i]+"\t");

                }

                System.out.println();

            }

        }

        catch (Exception e) {

            e.printStackTrace(); 

        }  

    }

}

写出一个Java程序,读取该CSV文件,并且按照部门字段分组,最后打印出来,打印结果如下:

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.util.ArrayList;

public class Sort {

public static void main(String[] args) throws Exception {

ArrayListString list = new ArrayListString();

File file = new File("data.csv"); //这里填你的csv文件的路径

BufferedReader fr = new BufferedReader(new FileReader(file));

String s = null;

while ((s=fr.readLine())!=null){

list.add(s);

}

fr.close();

list = sort(list);

for (String str : list){

System.out.println(str);

}

}

public static ArrayListString sort(ArrayListString list){

String str1 = null;

String str2 = null;

int flag = 0;

int size = list.size();

for(int i=0; ilist.size()-1; i++){

for (int j=0; jsize-1; j++){

str1 = list.get(j);

str2 = list.get(j+1);

flag = getDept(str1).compareToIgnoreCase(getDept(str2));

if (flag=0){

list.set(j, str2);

list.set(j+1, str1);

}

}

size -= 1;

}

return list;

}

public static String getDept(String str){

String[] array = str.split(",");

return array[3];

}

}

如何读取csv一行中的单个数据java

package com.han.csv.util;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

public class CSVFileUtil {

// CSV文件编码

public static final String ENCODE = "UTF-8";

private FileInputStream fis = null;

private InputStreamReader isw = null;

private BufferedReader br = null;

public CSVFileUtil(String filename) throws Exception {

fis = new FileInputStream(filename);

isw = new InputStreamReader(fis, ENCODE);

br = new BufferedReader(isw);

}

// ==========以下是公开方法=============================

/**

* 从CSV文件流中读取一个CSV行。

*

* @throws Exception

*/

public String readLine() throws Exception {

StringBuffer readLine = new StringBuffer();

boolean bReadNext = true;

while (bReadNext) {

//

if (readLine.length()  0) {

readLine.append("\r\n");

}

// 一行

String strReadLine = br.readLine();

// readLine is Null

if (strReadLine == null) {

return null;

}

readLine.append(strReadLine);

// 如果双引号是奇数的时候继续读取。考虑有换行的是情况。

if (countChar(readLine.toString(), '"', 0) % 2 == 1) {

bReadNext = true;

} else {

bReadNext = false;

}

}

return readLine.toString();

}

/**

*把CSV文件的一行转换成字符串数组。指定数组长度,不够长度的部分设置为null。

*/

public static String[] fromCSVLine(String source, int size) {

ArrayList tmpArray = fromCSVLinetoArray(source);

if (size  tmpArray.size()) {

size = tmpArray.size();

}

String[] rtnArray = new String[size];

tmpArray.toArray(rtnArray);

return rtnArray;

}

/**

* 把CSV文件的一行转换成字符串数组。不指定数组长度。

*/

public static ArrayList fromCSVLinetoArray(String source) {

if (source == null || source.length() == 0) {

return new ArrayList();

}

int currentPosition = 0;

int maxPosition = source.length();

int nextComma = 0;

ArrayList rtnArray = new ArrayList();

while (currentPosition  maxPosition) {

nextComma = nextComma(source, currentPosition);

rtnArray.add(nextToken(source, currentPosition, nextComma));

currentPosition = nextComma + 1;

if (currentPosition == maxPosition) {

rtnArray.add("");

}

}

return rtnArray;

}

/**

* 把字符串类型的数组转换成一个CSV行。(输出CSV文件的时候用)

*/

public static String toCSVLine(String[] strArray) {

if (strArray == null) {

return "";

}

StringBuffer cvsLine = new StringBuffer();

for (int idx = 0; idx  strArray.length; idx++) {

String item = addQuote(strArray[idx]);

cvsLine.append(item);

if (strArray.length - 1 != idx) {

cvsLine.append(',');

}

}

return cvsLine.toString();

}

/**

* 字符串类型的List转换成一个CSV行。(输出CSV文件的时候用)

*/

public static String toCSVLine(ArrayList strArrList) {

if (strArrList == null) {

return "";

}

String[] strArray = new String[strArrList.size()];

for (int idx = 0; idx  strArrList.size(); idx++) {

strArray[idx] = (String) strArrList.get(idx);

}

return toCSVLine(strArray);

}

// ==========以下是内部使用的方法=============================

/**

*计算指定文字的个数。

*

* @param str 文字列

* @param c 文字

* @param start  开始位置

* @return 个数

*/

private int countChar(String str, char c, int start) {

int i = 0;

int index = str.indexOf(c, start);

return index == -1 ? i : countChar(str, c, index + 1) + 1;

}

/**

* 查询下一个逗号的位置。

*

* @param source 文字列

* @param st  检索开始位置

* @return 下一个逗号的位置。

*/

private static int nextComma(String source, int st) {

int maxPosition = source.length();

boolean inquote = false;

while (st  maxPosition) {

char ch = source.charAt(st);

if (!inquote  ch == ',') {

break;

} else if ('"' == ch) {

inquote = !inquote;

}

st++;

}

return st;

}

/**

* 取得下一个字符串

*/

private static String nextToken(String source, int st, int nextComma) {

StringBuffer strb = new StringBuffer();

int next = st;

while (next  nextComma) {

char ch = source.charAt(next++);

if (ch == '"') {

if ((st + 1  next  next  nextComma)  (source.charAt(next) == '"')) {

strb.append(ch);

next++;

}

} else {

strb.append(ch);

}

}

return strb.toString();

}

/**

* 在字符串的外侧加双引号。如果该字符串的内部有双引号的话,把"转换成""。

*

* @param item  字符串

* @return 处理过的字符串

*/

private static String addQuote(String item) {

if (item == null || item.length() == 0) {

return "\"\"";

}

StringBuffer sb = new StringBuffer();

sb.append('"');

for (int idx = 0; idx  item.length(); idx++) {

char ch = item.charAt(idx);

if ('"' == ch) {

sb.append("\"\"");

} else {

sb.append(ch);

}

}

sb.append('"');

return sb.toString();

}

}

java 读取csv文件里指定行列的值,比如读取第三行第二列的值。

java读取csv文件,按照指定格式:

import java.io.IOException;

import java.nio.charset.Charset;

import java.util.ArrayList;

import com.csvreader.CsvReader;

import com.csvreader.CsvWriter;

/**

* 读取CSV文件

* 所谓"CSV",是Comma Separated Value(逗号分隔值)的英文缩写,通常都是纯文本文件。

* 可以看成数据库程序与电子表格之间一种中间通信文件,数据库可以导出。csv格式,excel也可以导入并打开。csv文件,例子如下

* sj_mino1001.jpg,715282,4FB55FE8,

* sj_mino1002.jpg,471289,93203C5C,

* sj_mino1003.jpg,451929,C4E80467,

*

*/

public class CSVDeal{

public static void main(String[] args) {

try {

String[] stringList;

String csvFilePath = "C:\\Users\\Administrator\\Desktop\\20140227135936.csv";

String sourceFileString= "C:\\Users\\Administrator\\Desktop\\test.csv";

CsvReader reader = new CsvReader(csvFilePath); //默认是逗号分隔符,UTF-8编码

CsvWriter writer = new CsvWriter(sourceFileString);

/*

* readRecord()判断是否还有记录,getValues()读取当前记录,然后指针下移

*/

reader.readRecord();

writer.writeRecord(reader.getValues()); //读取表头

/*

* 逐行读取,以免文件太大

* 处理表头后面的数据,这里是在第12列数据统一加前缀"V"

*/

while(reader.readRecord()){

stringList = reader.getValues();

stringList[11] = 'V' + stringList[11];

writer.writeRecord(stringList);

}

reader.close();

writer.close();

}catch(Exception ex){

System.out.println(ex);

}

}

}

java读取csv写入数据库

使用opencsv读到、、、、、使用jdbc存储数据库

~~~~~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~