Home > database >  JAVA - Parsing CSV File - Change delimiter
JAVA - Parsing CSV File - Change delimiter

Time:03-28

I have a problem and wanted to ask if someone can help me. I have a Java application that processes CSV files. The files have a semi-colon as a "delimiter". Now instead of semicolons I would like to use pipe "|" as the "delimiter". What is the best way to do this?

I have already informed myself in the library or class "org.apache.commons.csv.CSVRecord". Unfortunately couldn't find anything here.

CodePudding user response:

I used for parsing Spring Batch with the class FlatItemReaderBuilder.

You can also use Spring Batch classes in non Spring application.

Here you can find an example:

https://www.petrikainulainen.net/programming/spring-framework/spring-batch-tutorial-reading-information-from-a-file/

CodePudding user response:

you could use Scanner or FileInputStream

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ReadDelimited {
    public static void main(String[] args) {
    Scanner sc = null;
    try {
      sc = new Scanner(new File("D:\\acct.csv"));

      // Check if there is another line of input
      while(sc.hasNextLine()){
        String str = sc.nextLine();
        // parse each line using delimiter
        parseData(str);
      }
    } catch (IOException  exp) {
      // TODO Auto-generated catch block
      exp.printStackTrace();
    }finally{
      if(sc != null)
        sc.close();
    }           
  }
    
  private static void parseData(String str){    
    String acctFrom, acctTo, amount;
    Scanner lineScanner = new Scanner(str);
    lineScanner.useDelimiter("|");
    while(lineScanner.hasNext()){
      acctFrom = lineScanner.next();
      acctTo = lineScanner.next();
      amount = lineScanner.next();
      System.out.println("Account From- "   acctFrom   " Account To- "   acctTo   
       " Amount- "   amount);  
    }
    lineScanner.close();
  }
}

reference Code original link

or if File is not too large get the read the File in a string Divide it into a String array by splitting by line break and then future splitting using the delimiter of choice something like the code below.

public static void main(String[] args) throws IOException {

        FileInputStream fileInputStream=new FileInputStream("j:\\test.csv");

        String s1=new String(fileInputStream.readAllBytes());

        String[] lineArray=s1.split("\n");

        List<String[]> separatedValues=new ArrayList<>();

        for (String line: lineArray) {
            separatedValues.add(line.split("\\|"));
        }

        for (String[]  s: separatedValues) {
            for (String s2:s ) {
                System.out.print(s2 " ");
            }
            System.out.println("");
        }

        fileInputStream.close();

    }

Code Output Link

Original CSV

  • Related