需要引入javacsv.jar
以下为一个完整的Utils的写法,具体输出和输入需要自己修改参数。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Random; import org.springframework.util.StringUtils; import com.csvreader.CsvReader;
import com.csvreader.CsvWriter; /**
* 获取和写入csv文件内容
* <p>
* @author DennyZhao
* @since 1.0.0
*/
public class CSVUtils { /**
* 默认分隔符
*/
private static final char DEFAULT_SEPERATE_CHAR = ',';
/**
* 默认charset
*/
private static final Charset DEFAULT_CHARSET = Charset.defaultCharset(); /**
* 写数据
* @param targetFilePath
* @param fileName
* @param seperateChar
* @param charsetName
* @throws IOException
*/
public static void writeFile(String targetFilePath, String fileName, char seperateChar, String charsetName) throws IOException {
// 判断文件是否存在
File file = new File(targetFilePath);
if(!file.exists()) {
file.mkdirs();
}
// 判断是否有seperateChar
if(seperateChar == 0) {
seperateChar = DEFAULT_SEPERATE_CHAR;
}
// 判断是否有charset
Charset charset = DEFAULT_CHARSET;
if(!StringUtils.isEmpty(charsetName)) {
charset = Charset.forName(charsetName);
}
String filePath = targetFilePath + File.separatorChar + fileName;
// 获取csv文件及其数据
CsvWriter csvWriter = new CsvWriter(filePath, seperateChar, charset);
csvWriter.setForceQualifier(true); //这个决定了一般文件打开是不是有“”存在
String[] strHeader = {"userId","userName", "userAge"};
csvWriter.writeRecord(strHeader);
for(int i=0; i < 50; i++) {
String[] strArray = {i + "","张三" + i, (new Random()).nextInt(100) + ""};
csvWriter.writeRecord(strArray);
}
csvWriter.endRecord();
csvWriter.close();
} /**
* 读取csv文件中的数据
* @param originFile 要读入的文件
* @param seperateChar 分割符
* @param charsetName 编码格式
* @throws IOException
*/
public static void readFile(String originFile, char seperateChar, String charsetName) throws IOException {
// 判断文件是否存在
File file = new File(originFile);
if(!file.exists()) {
System.out.println("file is not exist...");
return;
}
// 判断是否有seperateChar
if(seperateChar == 0) {
seperateChar = DEFAULT_SEPERATE_CHAR;
}
// 判断是否有charset
Charset charset = DEFAULT_CHARSET;
if(!StringUtils.isEmpty(charsetName)) {
charset = Charset.forName(charsetName);
}
// 获取csv文件及其数据
CsvReader csvReader = new CsvReader(originFile, seperateChar, charset);
while(csvReader.readRecord()) {
//读取完毕
if(csvReader.getColumnCount() == 0) {
break;
}
long index = csvReader.getCurrentRecord(); //当前记录index
System.out.println("index: " + index);
if(index == 0) {
String[] headerArray = csvReader.getValues();
}
String userName = csvReader.get(1); //读取单条数据
String[] valArray = csvReader.getValues(); //读取数据变为数组
String recorder = csvReader.getRawRecord(); //直接读取一行数据
}
csvReader.close();
} public static void main(String[] args) throws IOException {
// 读数据
//String originFile = "C:\\Users\\zhaoq\\Desktop\\reader.csv";
//readFile(originFile, ',', "gb2312"); // 写数据
String targetFilePath = "C:\\Users\\zhaoq\\Desktop";
String fileName = "writer.csv";
writeFile(targetFilePath, fileName, ',', "gb2312");
} }