jeudi 29 octobre 2015

How to read Pipe delimited Line | from a File and Splitting Integers in two different ArrayList

The Program requires to interpret pipe delimited lines from a file and store it in two different ArrayLists. I have tried almost every related links on StackOverflow and came to know that | is a special operation and hence it is reserved. So I found several other ways to read the lines, but none of them actually works.

Here is my scenario:

The Text File looks like:

0|0.20
1|0.10
2|0.20

and so on...

The first Integer needs to go to ArrayList a1 and the second float number after the pipe delimiter need to go to ArrayList a2

I tried using scanner and them splitting the lines using split. Having saved them to a String and then doing the String conversion.I used following ways:

Method 1:

public static void readingFunc(String dirPath) throws  NumberFormatException, IOException{
    Path p = Paths.get(dirPath, "File.dat");
    for (String line: Files.readAllLines(p,StandardCharsets.US_ASCII)){
        for (String part : line.split("\\|")) {
            Integer i = Integer.valueOf(part);
            intArrayList1.add(i);
        }
    }

Method 2:

try(BufferedReader in = new BufferedReader(new FileReader(dirPath+"/File.dat"))){
          String line;
          while((line = in.readLine())!=null){
              String[] pair = line.split("\\|",-1);
              //a1.add(Integer.parseInt(pair[0]));
              //a2.add(Integer.parseInt(pair[1]))

Method 3:

try(BufferedReader in = new BufferedReader(new FileReader(dirPath+"/File.dat"))){
          String line;
          while((line = in.readLine())!=null){
              String[] pair = line.split("\\|",-1);

I also used several other Methods such as Scanner and couldn't get the result. I have several files similar to the one above and I need to read them to save it in an ArrayList for their processing.

PS: one of the file is having three data like:

1|0.21|0.37
2|0.08|0.12

and so on. I guess. this would be easy and similar to the two delimiter process. PS: I am developing on Linux Eclipse IDE so paths are:

/home/user/workspace1/Java_Code

I am sending the path as dirPath from the main function and then calling it here in a function. Please suggest me how to go with it?

I have checked already following Links:

Java Null value causing issue when reading a pipe delimited file

Read a file and split lines in Java.

Java - Scanner : reading line of record separated by Pipe | as delimiter

Java - putting comma separated integers from a text file into an array

Obtain number of token in a string with java Scanner

Aucun commentaire:

Enregistrer un commentaire