My input CSV having data like-
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
I want to read each line from my CSV and create a New CSV/TXT file for each line. Like- For row 1 one file will be created called 1.txt/1.csv which will be holding all row 1 data. Same for row 2 and so on.. How in java we can achieve this?
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(); } }
Advertisement
Answer
You should count the lines in the input file, not the length of current line:
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(); }