CSV是以逗号间隔的文本文件,其文件以纯文本形式存储表格数据(数字和文本)。在JAVA中可以通过输出文件流的方式将数据写入CSV文件,通过BufferedReader类去读该路径中的文件,使用readLine方法进行逐行读取。

  •   写csv文件需要注意

  1、如果需要重复写文件,需要考虑删除已经存在的文件。

  •   读csv文件需要注意:

  1、文件路径是否存在

  2、文件表头是否正确,考虑兼容性问题时,只需要考虑是否存在需要的列即可

第一步:创建一个对象类

 package testCSV;

 public class Person {
private String id;
private String name;
private String sex;
private int age; public Person() {
} public Person(String id, String name, String sex, int age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
}

第二步:写和读csv文件

 package testCSV;

 import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; public class FileCsv {
private static final String fileName = "D:\\workspace\\tmp\\obj.csv";
private static final String CSV_SPLIT = ",";
private static int idIndex = -1;
private static int nameIndex = -1;
private static int sexIndex = -1;
private static int ageIndex = -1; /**
* 生成uuid
*
* @return 32位uuid
*/
private static String getUUID32() {
return UUID.randomUUID().toString().replace("-", "").toLowerCase();
} /**
* 构造数据
*
* @return 数据
*/
private static List<Person> buildData() {
List<Person> personList = new ArrayList<Person>(10);
personList.add(new Person(getUUID32(), "张三", "female", 26));
personList.add(new Person(getUUID32(), "李四", "man", 34));
personList.add(new Person(getUUID32(), "王五", "female", 55));
personList.add(new Person(getUUID32(), "一一", "female", 11));
return personList;
} /**
* 写csv文件
*
* @return 文件名
*/
public static String writeCsv() {
File file = new File(fileName);
if (null != file && file.exists()) {
file.delete();
}
List<Person> personList = buildData();
FileOutputStream out = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
out = new FileOutputStream(file);
osw = new OutputStreamWriter(out, "UTF-8");
bw = new BufferedWriter(osw);
String title = "ID,NAME,SEX,AGE\r";
bw.append(title); for (Person data : personList) {
bw.append(data.getId());
bw.append(CSV_SPLIT);
bw.append(data.getName());
bw.append(CSV_SPLIT);
bw.append(data.getSex());
bw.append(CSV_SPLIT);
bw.append(String.valueOf(data.getAge()));
bw.append("\r");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (bw != null) {
try {
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (osw != null) {
try {
osw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return fileName;
} /**
* 表头正确性校验
*
* @param titleInfo 表头
* @return
*/
private static Boolean checkTitle(String titleInfo) {
if (null == titleInfo || titleInfo.isEmpty()) {
return false;
}
String[] titles = titleInfo.split(CSV_SPLIT);
for (int i = 0; i < titles.length; i++) {
String titleName = titles[i];
if (titleName.equals("ID")) {
idIndex = i;
continue;
}
if (titleName.equals("NAME")) {
nameIndex = i;
continue;
}
if (titleName.equals("SEX")) {
sexIndex = i;
continue;
}
if (titleName.equals("AGE")) {
ageIndex = i;
continue;
}
}
if (idIndex == -1
|| nameIndex == -1
|| sexIndex == -1
|| ageIndex == -1) {
return false;
}
return true;
} /**
* 读取csv文件
*
* @return 数据
*/
private static List<Person> readCsv() {
File file = new File(fileName);
if (null == file) {
return new ArrayList<Person>();
}
if (!file.exists()) {
return new ArrayList<Person>();
}
BufferedReader bufferedReader = null;
List<Person> personList = new ArrayList<Person>(10);
try {
bufferedReader = new BufferedReader(new FileReader(file));
if (!checkTitle(bufferedReader.readLine())) {
return new ArrayList<Person>();
}
String line = "";
while (null != (line = bufferedReader.readLine())) {
String[] personInfo = line.split(CSV_SPLIT);
Person person = new Person();
person.setId(personInfo[idIndex]);
person.setName(personInfo[nameIndex]);
person.setSex(personInfo[sexIndex]);
person.setAge(Integer.parseInt(personInfo[ageIndex]));
personList.add(person);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return personList;
} public static void main(String[] args) {
writeCsv();
List<Person> personList = readCsv();
for (int i = 0; i < personList.size(); i++) {
Person person = personList.get(i);
System.out.println("id=" + person.getId()
+ ",name=" + person.getName()
+ ",sex=" + person.getSex()
+ ",age=" + String.valueOf(person.getAge()));
}
}
}
结果验证:
写文件
读文件

如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!
 
 

读写csv文件——考虑各种异常场景,源码的更多相关文章

  1. 使用Python读写csv文件的三种方法

    Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是 ...

  2. python读写csv文件

    文章链接:https://www.cnblogs.com/cloud-ken/p/8432999.html Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗 ...

  3. 用opencsv文件读写CSV文件

    首先明白csv文件长啥样儿: 用excel打开就变成表格了,看不到细节 推荐用其它简单粗暴一点儿的编辑器,比如Notepad++, csv文件内容如下: csv文件默认用逗号分隔各列. 有了基础的了解 ...

  4. python3读写csv文件

    python读取CSV文件   python中有一个读写csv文件的包,直接import csv即可.利用这个python包可以很方便对csv文件进行操作,一些简单的用法如下. 1. 读文件 csv_ ...

  5. 利用JavaCSV API来读写csv文件

    http://blog.csdn.net/loongshawn/article/details/53423121 http://javacsv.sourceforge.net/ 转载请注明来源-作者@ ...

  6. 使用 Apache Commons CSV 读写 CSV 文件

    有时候,我们需要读写 CSV 文件,在这里给大家分享Apache Commons CSV,读写 CSV 文件非常方便. 具体官方文档请访问Apache Commons CSV. 官方文档已经写得很详细 ...

  7. python3使用csv包,读写csv文件

    python操作csv,现在很多都用pandas包了,不过python还是有一个原始的包可以直接操作csv,或者excel的,下面举个例子说明csv读写csv文件的方法: import os impo ...

  8. C/C++读写csv文件

    博客转载自:http://blog.csdn.net/u012234115/article/details/64465398 C++ 读写CSV文件,注意一下格式即可 #include <ios ...

  9. JAVA读写CSV文件

    最近工作需要,需要读写CSV文件的数据,简单封装了一下 依赖读写CSV文件只需引用`javacsv`这个依赖就可以了 <dependency> <groupId>net.sou ...

随机推荐

  1. KVM性能优化学习笔记

    本学习笔记系列都是采用CentOS6.x操作系统,KVM虚拟机的管理也是采用virsh方式,网上的很多的文章都基于ubuntu高版本内核下,KVM的一些新的特性支持更好,本文只是记录了CentOS6. ...

  2. sprintf与strcat

    sprintf可以将整数转化为字符串,也可以连接两个字符串.但是用sprintf在连接两个字符串时,容易出现错误. 因此连接两个字符串时候用strcat, 将整数转化为字符串时候用sprintf. 转 ...

  3. 【2】JMicro微服务-Hello World

    如非授权,禁止用于商业用途,转载请注明出处作者:mynewworldyyl 1. 首先完成 JMicro微服务-RPC体验 的1到5步. 按默认方式启动ZK及Redis: JDK需要Java8及以上. ...

  4. Linux修改profile文件改错了,恢复的方法

    Linux修改profile文件改错了,恢复的方法在改profile的时候,改出问题了,除了cd以外的命令基本都不能用了,连vi都不能用了,上网查了下,用export PATH=/usr/bin:/u ...

  5. Java NIO学习与记录(一):初识NIO

    初识 工作中有些地方用到了netty,netty是一个NIO框架,对于NIO却不是那么熟悉,这个系列的文章是我在学习NIO时的一个记录,也期待自己可以更好的掌握NIO. 一.NIO是什么? 非阻塞式I ...

  6. ubuntu 16.04安装后的简单优化

    1.更换更新源为国内源: sudo vim /etc/apt/sources.list vim 打开更新源配置文件添加国内源进去,这里添加阿里源 deb http://mirrors.aliyun.c ...

  7. es6里class类

    /** * Created by issuser on 2018/11/27. *///如果静态方法包含this关键字,这个this指的是类,而不是实例./** (1)类的实例属性 1.类的实例属性可 ...

  8. shell脚本杀进程重启

    #!/bin/bash ID=`ps -ef | grep "abc" | grep -v "$0" | grep -v "grep" | ...

  9. JavaScript设计模式-4.继承和聚合

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  10. js解决千分符问题

    js脚本function: //js数字千分符处理 function commafy(num) { num = num + ""; var re = /(-?\d+)(\d{3}) ...