java - 有没有办法使用 CSVParser 为 CSV 文件添加自定义分隔符?
问题描述
目前,我正在使用本教程来了解如何读取 CSV 文件:https : //stackabuse.com/reading-and-writing-csvs-in-java-with-apache-commons-csv/ 它使用了 Apache 的 CSVParser 和 CSVFormat-公共-csv。
它可以很好地阅读,但不是我想要的方式。在我检查了它为什么不起作用的原因后发现我的 CSV 文件有分隔符“|” 而不是 "," 并且 CSVParser 无法读取它。有没有办法让我将 CSVParser 的分隔符更改为“|” 代替 ”,”?我真的很想使用这种方法,因为record.get("name of the map")
我正在做的这个项目对我有很大帮助,我不想手动更改 CSV 文件。
这是我当前的代码:
@PostMapping("/uploadFile")
public static void uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException{
if(file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) {
InputStreamReader input = new InputStreamReader(file.getInputStream());
CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(input);
for (CSVRecord record : csvParser) {
System.err.println(record.get("nameOftheColumn"));
}
response.sendRedirect("/rekonsiliasi");
}
else {
response.sendRedirect("/rekonsiliasi");
}
}
任何形式的帮助表示赞赏。
解决方案
你试过用
CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().withDelimiter('|').parse(input);
有关相关 JavaDoc,请参阅http://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html#withDelimiter-char-。
推荐阅读
- flutter - 在 null 上调用了 getter 'address'。蓝牙连接到设备 flutter_bluetooth_serial
- excel - 如何将每张工作表的多个 excel 文件聚合(合并)到一个主文件中?
- python - Python - 将字符串转换为 Int 以便在函数内进行比较
- python - k 值连续误差。基础模型训练题
- javascript - Webpack 插件 v5 existsAt 在编译对象中不存在
- python - 获取 selenium 中多个标签的所有子元素
- javascript - 如何在 vue js 3 中使用 v-bind:style 根据 ref id 操作特定元素的 css 样式
- python - 带有 __init__.py 的 Python 模块和包
- python - 在一个源代码中,我输入它并得到: UserWarning: Matplotlib is current is using agg, which is an non-GUI backend, so cannot show the figure
- javascript - Angular Spinner 无限循环,而路由器插座中的 ngIf