java - 从 CSV 文件读取并将每一行写入不同的文件
问题描述
我的输入 CSV 具有如下数据 -
VBS123ER,Abc_123,TEST_REPORT_FOR_SA,15-JUN-2020,76854,SAMPLE_REPORT
VBS123ER,Abc_123,TEST_REPORT_FOR_SA,15-JUN-2020,76855,SAMPLE_REPORT
我想从我的 CSV 中读取每一行并为每一行创建一个新的 CSV/TXT 文件。Like- 对于第 1 行,将创建一个名为 1.txt/1.csv 的文件,该文件将保存所有第 1 行数据。第 2 行也一样,依此类推。在 java 中我们如何实现这一点?
File f = new File("C:\\Test\\AR_POC\\Input.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
System.out.println("Reading file using Buffered Reader");
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
for(int i = 0; i < readLine.length; i++) {
FileOutputStream fo = new FileOutputStream("C:\\Test\\AR_POC\\" + Name + i + ".txt");
fo.write(readLine.getBytes());
fo.close();
}
}
解决方案
您应该计算输入文件中的行数,而不是当前行的长度:
File f = new File("C:\\Test\\AR_POC\\Input.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
System.out.println("Reading file using Buffered Reader");
int i = 0;
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
FileOutputStream fo = new FileOutputStream("C:\\Test\\AR_POC\\" + Name + i++ + ".txt");
fo.write(readLine.getBytes());
fo.close();
}
推荐阅读
- mysql - 无法使用套接字连接到 Google Cloud SQL,但可以使用 IP 地址连接
- javascript - 正则表达式从 Javascript 到 MySQL
- database - HANA 中的 ADBC 临时表
- windows - 按不同的 UserId 将 CSV 文件拆分为单独的文件
- c - 'void scan_fraction(int*, int*)' 的新声明含糊不清
- validation - 是否可以让人们仅在具有 VIEW 权限的 Google 工作表上打开滚动菜单?
- mysql - Hibernate 在使用 springboot 运行的现有表上创建新列
- python - 使用 .isin() pandas (python) 测试的列中的替代值
- html - 如何防止div内的属性使用项目的css
- mysql - 用引号更新部分文本