java实现CSV文件的导入导出操作
Posted xieweikun7
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java实现CSV文件的导入导出操作相关的知识,希望对你有一定的参考价值。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
/**
* CSV操作(导出和导入)
*/
public class CSVUtils
public static void main(String[] args)
List<String> dataList = new ArrayList<String>();
dataList.add("1,张三,男");
dataList.add("2,李四,男");
dataList.add("3,小红,女");
boolean isSuccess = CSVUtils
.exportCsv(new File("F:/test.csv"), dataList);
System.out.println(isSuccess);
/**
* 导出数据到csv文件
* @param file csv文件(路径+文件名),csv文件不存在会自动创建
* @param dataList 数据
* @return
*/
public static boolean exportCsv(File file, List<String> dataList)
boolean isSucess = false;
FileOutputStream out = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try
out = new FileOutputStream(file);
osw = new OutputStreamWriter(out);
bw = new BufferedWriter(osw);
if (dataList != null && !dataList.isEmpty())
for (String data : dataList)
bw.append(data).append("\\r");
isSucess = true;
catch (Exception e)
isSucess = false;
finally
if (bw != null)
try
bw.close();
bw = null;
catch (IOException e)
e.printStackTrace();
if (osw != null)
try
osw.close();
osw = null;
catch (IOException e)
e.printStackTrace();
if (out != null)
try
out.close();
out = null;
catch (IOException e)
e.printStackTrace();
return isSucess;
/**
* 导入csv数据
* @param file csv文件(路径+文件)
* @return
*/
public static List<String> importCsv(File file)
List<String> dataList = new ArrayList<String>();
BufferedReader br = null;
try
br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null)
dataList.add(line);
catch (Exception e)
finally
if (br != null)
try
br.close();
br = null;
catch (IOException e)
e.printStackTrace();
return dataList;
以上是关于java实现CSV文件的导入导出操作的主要内容,如果未能解决你的问题,请参考以下文章