问题场景,公司需求对图片表数据进行分析(大小,像素,长,宽),以CSV形式进行操作.
1.准备操作
Maven
<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
API 说明文档:http://javacsv.sourceforge.net/
JavaCSV官网:https://sourceforge.net/projects/javacsv/
javacsv-2.1.jar点击下载
2.代码展示
package com.dongshuo;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* @author dongshuo
* @data 2018/5/31 17:51
* @Description csv 文件读写操作
*/
public class CSVUtil {
//static String readPath = "D:/image/p_sku_pop_relation.csv";
/**
* 读取每行的数据
*
* @param readPath
* @return
*/
public static List<String> readCSV(String readPath) {
String filePath = readPath;
List<String> listData = new ArrayList<>();
try {
filePath = readPath;
CsvReader csvReader = new CsvReader(filePath);
// 读表头
boolean re = csvReader.readHeaders();
while (csvReader.readRecord()) {
String rawRecord = csvReader.getRawRecord();
listData.add(rawRecord);
}
return listData;
} catch (FileNotFoundException e) {
throw new RuntimeException("文件未找到");
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 写入文件头
* @param writePath
* @param header
*/
public static void writeCSV(String writePath, String[] header) {
String filePath = writePath;
try {
CsvWriter csvWriter = new CsvWriter(writePath, ',', Charset.forName("UTF-8"));
//String [] header = {"SkuId","SsuId","图片地址","大小(bit)","高度","宽度"};
csvWriter.writeRecord(header);
csvWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 利用输入输出流持续写
* @param fileName
* @param content
*/
public static void writeContent(String fileName, String content) {
FileWriter writer = null;
try {
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
writer = new FileWriter(fileName, true);
writer.write(content + "\r\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我翻阅了文档javacsv不支持追加写,所以采用的输出流完成追加写
为了提高速度,采用多线程,并发执行