CSV其实就是COMMA SEPARATED VALUE的缩写。
在开发中用Java操作csv文件有专门的的API叫javacsv.jar

javacsv.jar下载地址:
http://sourceforge.net/project/showfiles.php?group_id=33066

下面演示一段操作代码仅供参考:

Java代码
package com.syc.test.bean;

public class ReslutBean {
String help_keyword_id;
String name;

public String getHelp_keyword_id() {
return help_keyword_id;
}
public void setHelp_keyword_id(String help_keyword_id) {
this.help_keyword_id = help_keyword_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Java代码
package com.syc.test.javaCSV;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.syc.test.DAO.ConnectionDB;
import com.syc.test.bean.ReslutBean;

public class JavaCSV {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// 从获取将要写入csv文件的结果集
List<ReslutBean> list = new ArrayList<ReslutBean>();
list = ConnectionDB.querySQL();

// 预组装csv文件内容标题行
String[][] data = new String[list.size() + 1][2];
data[0][0] = "Help_keyword_id";
data[0][1] = "Name";

// 预组装csv文件内容
int len = list.size();
for (int i = 0; i < len; i++) {
data[i + 1][0] = list.get(i).getHelp_keyword_id();
data[i + 1][1] = list.get(i).getName();
}

writerCsv("e://c测试.csv", data);
readerCsv("e://c测试.csv");
}

/**
* 读取csv
*
* @param csvFilePath
* @throws Exception
*/
public static void readerCsv(String csvFilePath) throws Exception {

CsvReader reader = new CsvReader(csvFilePath, ',',
Charset.forName("GBK"));// shift_jis日语字体,utf-8
reader.readHeaders();
String[] headers = reader.getHeaders();

List<Object[]> list = new ArrayList<Object[]>();
while (reader.readRecord()) {
list.add(reader.getValues());
}
Object[][] datas = new String[list.size()][];
for (int i = 0; i < list.size(); i++) {
datas[i] = list.get(i);
}

/*
* 以下输出
*/

for (int i = 0; i < headers.length; i++) {
System.out.print(headers[i] + "\t");
}
System.out.println("");

for (int i = 0; i < datas.length; i++) {
Object[] data = datas[i]; // 取出一组数据
for (int j = 0; j < data.length; j++) {
Object cell = data[j];
System.out.print(cell + "\t");
}
System.out.println("");
}
}

/**
* 写入csv
*
* @param csvFilePath文件名路径
* +文件名字
* @param data数据项
*/
public static void writerCsv(String csvFilePath, String[][] data) {

CsvWriter writer = null;
try {
writer = new CsvWriter(csvFilePath, ',', Charset.forName("GBK"));// shift_jis日语字体,utf-8

for (int i = 0; i < data.length; i++) {
writer.writeRecord(data[i]);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
writer.close();
}
}
}

当然你还可以用supecsv 或者 opencsv啦。

先下载javacsv2.0.zip的文件,解压后,把javacsv.jar 添加到项目中。

官方下载地址:
http://sourceforge.net/project/showfiles.php?group_id=33066

API地址:

http://javacsv.sourceforge.net/
简单的操作代码:

Java代码
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

public class DB2ExportCsv
{
/**
* 读取CSV文件
*/
public void readCsv(){
try {
ArrayList<String[]> csvList = new ArrayList<String[]>(); //用来保存数据
String csvFilePath = "D:/log/Alarm20101125.csv";
CsvReader reader = new CsvReader(csvFilePath,',',Charset.forName("SJIS")); //一般用这编码读就可以了

reader.readHeaders(); // 跳过表头 如果需要表头的话,不要写这句。

while(reader.readRecord()){ //逐行读入除表头的数据
csvList.add(reader.getValues());
}
reader.close();

for(int row=0;row<csvList.size();row++){
String cell = csvList.get(row)[0]; //取得第row行第0列的数据
System.out.println(cell);
}
} catch (Exception ex) {
System.out.println(ex);
}
}

/**
* 写入CSV文件
*/
public static void WriteCsv(){
try {
String csvFilePath = "D:/log/Alarm20101125.csv";
CsvWriter wr =new CsvWriter(csvFilePath,',',Charset.forName("SJIS"));
String[] contents = {"告警信息","非法操作","没有权限","操作失败"};
wr.writeRecord(contents);
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

想了解更多的函数请查看javacsv2.0/doc/index.html说明。我觉得javacsv2.0/src/AllTests.java看看也很有用。大家可以去试试

此代码可以解决字段中出现分隔符,双引号等等。。。

Java代码
/**
* 对于文件中字段包含逗号的文件的特殊处理 (同时可以去除掉双引号)处理完以后会在相同的路径下输出相同文件名的TXT文件
*
* @throws Exception
*/
public static void specialChar(String filePath,int starRow) throws Exception {

BufferedReader br = null;
File f = new File(filePath);
String fileName = f.getName();

if (!fileName.substring(fileName.indexOf(".") + 1).equals("csv")) {
throw new Exception(filePath + "不是一个CSV文件");
}
File file = new File(StringUtil.replace(f.getPath(), "csv", "txt"));
FileWriter filewriter = null;
try {
br = new BufferedReader(new InputStreamReader(
new FileInputStream(f), "utf-8"));
filewriter = new FileWriter(file, false);
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

System.out.println(sd.format(new Date()));
String tempString = null;
int i = 0;
while ((tempString = br.readLine()) != null) {
if (i < starRow-1) {
i++;
continue;
}
if(tempString.trim().equals(""))
break;
if (StringUtil.contains(tempString, "\"")) {
tempString = deepParser(tempString,filePath);
} else
tempString = StringUtil.replace(tempString, ",", "|");
// System.out.println(tempString);
filewriter.write(stringTrim(tempString, "\\|") + "\r\n");
i++;
}
System.out.println(sd.format(new Date()));
} catch (Throwable e) {
log.warn("解析文件:【" + filePath + "】出错", e);
e.printStackTrace();
} finally {
try {
br.close();
filewriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

public static String deepParser(String str,String filePath) {
System.out.println(str);
String temp = str;
str = str+",";
StringBuffer sb = new StringBuffer();
try {
int from = 0;
int end = str.length();
int i = 0;
while (StringUtil.contains((str = str.substring(from)), "\"")) {
from = str.indexOf("\"");
end = str.indexOf("\"", from + 1);
sb.append(StringUtil.replace(str.substring(0, from), ",", "|"));
sb.append(str.substring(from + 1, end));
from = end + 1;
i++;
}
sb.append(StringUtil.replace(str, ",", "|"));
} catch (Throwable e) {
log.warn("解析文件:【" + filePath + "】出错,一下数据有问题:"+temp, e);
e.printStackTrace();
}
String s = sb.toString();
s = s.substring(0, s.lastIndexOf("|"));
return s;
}

//去除字段2边空格,可以指定分隔符
public static String stringTrim(String str, String regex) {
str = str+" ";
String[] strs = str.split(regex);
StringBuffer sb = new StringBuffer();

for (int i = 0; i < strs.length; i++) {
sb.append(strs[i].trim() + "|");
}

return sb.toString().substring(0, sb.toString().lastIndexOf("|"));
}

java读取scv文件相关推荐

  1. java 读取txt,java读取大文件

    java 读取txt,java读取大文件 package com.bbcmart.util; import java.io.File; import java.io.RandomAccessFile; ...

  2. Java基础学习总结(15)——java读取properties文件总结

    2019独角兽企业重金招聘Python工程师标准>>> 一.java读取properties文件总结 在java项目中,操作properties文件是经常要做的,因为很多的配置信息都 ...

  3. java读取本地文件_java 读取本地文件实例详解

    java 读取本地文件实例详解 用javax.xml.w3c解析 实例代码: package cn.com.xinli.monitor.utils; import org.w3c.dom.Docume ...

  4. java 读取css文件_java文件读取的两种方式

    JAVA中读取文件(二进制,字符)内容的几种方 JAVA中读取文件内容的方法有很多,比如按字节读取文件内容,按字符读取文件内容,按行读取文件内容,随机读取文件内容等方法,本文就以上方法的具体实现给出代 ...

  5. java读取XML文件的四种方式

    java读取XML文件的四种方式 Xml代码 <?xml version="1.0" encoding="GB2312"?> <RESULT& ...

  6. 用java读取properties文件--转

    今天为了通过java读取properties文件,google了很长时间,终于找到了.现在特记录之和大家一起分享.      下面直接贴出代码:java类 public class Mytest pu ...

  7. [java进阶]1.Java读取txt文件和写入txt文件

    1. Java读取txt文件 import java.io.*; import java.util.ArrayList; import java.util.List;public class unit ...

  8. java读取TXT文件的方法

    java读取txt文件内容.可以作如下理解: 首先获得一个文件句柄.File file = new File(); file即为文件句柄.两人之间连通电话网络了.接下来可以开始打电话了. 通过这条线路 ...

  9. JNI开发笔记(八)--Java读取txt文件进行JNI测试

    Java读取txt文件进行JNI测试 引 前言 1. 新建assets文件夹 2. 载入测试文件 3. 建立文件读取方法 4. 在MainActivity中读取文件数据 引 JNI开发笔记(一)–An ...

  10. java inireader_用Java读取INI文件(带section的)

    代码 #include #include int main(){ boost::property_tree::ptree m_pt, tag_setting; read_ini("confi ...

最新文章

  1. 配深度学习环境要注意的不多,也就
  2. Requirement already satisfied 解决方法
  3. java生成公钥和私钥_使用Java生成证书,公钥和私钥
  4. 【JDBC】实现对JDBC 连接的简单封装
  5. ES6新特征总结与介绍——声明与表达式
  6. mysql数据库参考_干货:MySQL数据库优化参考
  7. 浅谈 JavaScript、ECMAScript (ES5、ES6)是什么、相互关系
  8. cad缩放工具怎么用_小米电视怎么投屏?这个投屏工具真的太好用啦!
  9. paddleocr常见问题(3)
  10. mysq show 指令
  11. springboot热部署之spring-boot-devtools
  12. 不要让Javascript的等价表格看上去那么难看
  13. redis学习笔记1-NoSQL概述
  14. 解决Visual Studio 2022 python 中文乱码问题
  15. open 3D 点云兔子模型
  16. 计算机wifi怎么打不开,电脑的wifi打不开了怎么办
  17. 教师继续教育 计算机知识,教师继续教育管理制度
  18. python提取关键词_【Python工具】30万关键词提取疑问词只需2秒,效率高到飞起!...
  19. #微信小程序# 在小程序里面退出退出小程序(navigator以及API--wx.exitMiniProgram)
  20. NC57中间表数据源的设置流程

热门文章

  1. Windows安装Svn客户端
  2. 均匀B样条和准均匀B样条
  3. Locust (二)接口压力测试
  4. “一键淘宝”将淘宝网店免费转移到手机客户端教程
  5. visio绘制自定义图形(完全零基础)
  6. 全国计算机等级考试一级模拟考,全国计算机等级考试一级模拟试题一
  7. 手机分辨率和网页中的px是一回事吗?
  8. 【PCBA方案】咖啡电子秤芯片方案介绍
  9. [转]java代码混淆以及及IDEA中springboot使用Allatori进行混淆
  10. 低代码平台- Intellij IDEA 插件开发