读写csv文件——考虑各种异常场景,源码
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文件——考虑各种异常场景,源码的更多相关文章
- 使用Python读写csv文件的三种方法
Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是 ...
- python读写csv文件
文章链接:https://www.cnblogs.com/cloud-ken/p/8432999.html Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗 ...
- 用opencsv文件读写CSV文件
首先明白csv文件长啥样儿: 用excel打开就变成表格了,看不到细节 推荐用其它简单粗暴一点儿的编辑器,比如Notepad++, csv文件内容如下: csv文件默认用逗号分隔各列. 有了基础的了解 ...
- python3读写csv文件
python读取CSV文件 python中有一个读写csv文件的包,直接import csv即可.利用这个python包可以很方便对csv文件进行操作,一些简单的用法如下. 1. 读文件 csv_ ...
- 利用JavaCSV API来读写csv文件
http://blog.csdn.net/loongshawn/article/details/53423121 http://javacsv.sourceforge.net/ 转载请注明来源-作者@ ...
- 使用 Apache Commons CSV 读写 CSV 文件
有时候,我们需要读写 CSV 文件,在这里给大家分享Apache Commons CSV,读写 CSV 文件非常方便. 具体官方文档请访问Apache Commons CSV. 官方文档已经写得很详细 ...
- python3使用csv包,读写csv文件
python操作csv,现在很多都用pandas包了,不过python还是有一个原始的包可以直接操作csv,或者excel的,下面举个例子说明csv读写csv文件的方法: import os impo ...
- C/C++读写csv文件
博客转载自:http://blog.csdn.net/u012234115/article/details/64465398 C++ 读写CSV文件,注意一下格式即可 #include <ios ...
- JAVA读写CSV文件
最近工作需要,需要读写CSV文件的数据,简单封装了一下 依赖读写CSV文件只需引用`javacsv`这个依赖就可以了 <dependency> <groupId>net.sou ...
随机推荐
- forword和重定向有什么区别?
一.forword 1.请求只能从同一个web中转发,当前应用之外的找不到. 2.地址栏不变. 3.共享request对象,请求链不断. 4.永久性跳转,最常用. 5.客户端方法功能跳转 二.重定向 ...
- 鸡肋点搭配ClickJacking攻击-获取管理员权限
作者:jing0102 前言 有一段时间没做测试了,偶尔的时候也会去挖挖洞.本文章要写的东西是我利用ClickJacking拿下管理员权限的测试过程.但在说明过程之前,先带大家了解一下ClickJac ...
- Error: Cannot find module 'gulp-sass'
刚才首次启动ionic的时候,给我报了个这:Error: Cannot find module 'gulp-sass' 应该是缺少gulp-sass模块了,可又不敢贸然装,直接百度: stackove ...
- MQ 消息队列的比较
目前业界有很多MQ产品,我们作如下对比: RabbitMQ 是使用Erlang编写的一个开源的消息队列,本身支持很多的协议:AMQP,XMPP, SMTP, STOMP,也正是如此,使的它变的非常重量 ...
- Tomcat启动和请求处理解析
tomcat是我们经常使用的组件,但是内部是如何运行的呢,我们去一探究竟. 1.tomcat架构 tomcat的整体架构图如下: Tomcat中只有一个Server,一个Server可以有多个Serv ...
- vscode 本地调试nodejs
1.首先通过node-inspect插件可以debug nodejs ,先起nodejs服务,再启用node-inpector服务 安装调试器 npm install -g node-inspec ...
- leetcode-292-Nim Game(搬石子)
题目描述: You are playing the following Nim Game with your friend: There is a heap of stones on the tabl ...
- 架构师养成记--21.netty编码解码
背景 作为网络传输框架,免不了哟啊传输对象,对象在传输之前就要序列化,这个序列化的过程就是编码过程.接收到编码后的数据就需要解码,还原传输的数据. 代码 工厂类 import io.netty.han ...
- Centos7 DNS神奇的配置
文件 [root@iff etc]# cat /etc/named.conf // // named.conf // // Provided by Red Hat bind package to co ...
- Python数据结构之序列及其操作
数据结构是计算机存储,组织数据的方式.数据结构是指相互之间存在一种或多种特定关系的数据元素的集合. 在Python中,最基本的数据结构为序列(sequence).序列中的每个元素都有编号:从0开始递增 ...