java导入csv自动识别字符集(JAVA解析生成CSV文件)
一、引入pom依赖<!-- CSV -->
<dependency>
<groupId>net.sourceforge.javaCsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
,下面我们就来聊聊关于java导入csv自动识别字符集?接下来我们就一起去了解一下吧!
java导入csv自动识别字符集
一、引入pom依赖
<!-- CSV -->
<dependency>
<groupId>net.sourceforge.javaCsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
二、解析CSV文件
import com.csvreader.CsvReader;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileNotFoundexception;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* cvs读取
*/
public class CsvReaderUtil1 {
private static final String PARSE_ERROR = "csv analysis exception {}";
public static List<String[]> processFile(MultipartFile file, int dataIndex)
throws IOException {
// 创建CSV读对象
return processInputStream(file.getInputStream(), dataIndex);
}
public static List<String[]> processPath(String path, int dataIndex)
throws FileNotFoundException {
// 创建CSV读对象
CsvReader csvReader = new CsvReader(path, ',', Charset.forName("gbk"));
return process(csvReader, dataIndex);
}
public static List<String[]> processInputStream(InputStream inputStream, int dataIndex) {
// 创建CSV读对象
CsvReader csvReader = new CsvReader(inputStream, ',', Charset.forName("gbk"));
return process(csvReader, dataIndex);
}
private static List<String[]> process(CsvReader csvReader, int dataIndex) {
//总数据
List<String[]> dataList = new ArrayList<>();
try {
while (csvReader.readRecord()) {
if (csvReader.getCurrentRecord() >= dataIndex) {
// 读取一行的单元格
String[] row = csvReader.getValues();
for (int i = 0; i < row.length; i ) {
if (isEmpty(row[i])) {
row[i] = "";
} else {
row[i] =
row[i].replaceAll(",", ",").replaceAll("\n", "");
}
}
dataList.add(row);
}
}
csvReader.close();
return dataList;
} catch (IOException e) {
e.printStackTrace();
}
return dataList;
}
public static boolean isEmpty(String str) {
return str == null || str.trim().length() == 0;
}
}
二、生成CSV文件
import com.base.infrastructure.log.LoggerManager;
import com.csvreader.CsvWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
public class CsvWriterUtil {
public static void process(List<String[]> data, String filePath) {
LoggerManager.info(CsvWriterUtil.class, "wirte csv start......filepath:{}", filePath);
CsvWriter csvWriter = null;
try {
csvWriter = new CsvWriter(filePath, ',', Charset.forName("utf-8"));
for (String[] values : data) {
csvWriter.writeRecord(values);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (csvWriter != null) {
csvWriter.close();
}
}
}
}
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com