简体   繁体   中英

Read from a CSV file and write each line into a Different File

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(); 
    } 
}

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(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM