Home > OS >  How to read a csv like text file in Java and store each line individually?
How to read a csv like text file in Java and store each line individually?

Time:08-25

I have a text file which is like a csv but each line ends with a "/" delimeter. Now, i can store the whole file in a string, then split it at (/) and i get each individual line, but i cant print it. Once i get a line, if want to verify, if some field matches certain value, i cant make it work? Each line starts with a number, say 01 or 04 or 06 and each records can repeat many times...like there can be in hundreds...So, i want to say look for 06 records and find if its 3rd index matches a string or is equal to "333" value. How, do i do that?

And some records dont end with a delimiter, how to store those records

01,93493,TEST,333,1233,23434,,,ABC/
04,3434,TEST2,333,1233,34343,,,TEXT22/
04,3434,TEST3,333,1233,020202,,,DEFT/
01,464536,TEST4,,1233,88,,,CCEA/
03,34623,TEST4,333,1233,3434,,,LINE2/
03,34623,TEST4,333,1233,3434,,,LINE2/
06,34623,TEST4,333,1233,3434,
06,34623,TEST4,333,1233,3434,



File file = new File("file1.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line = " ";
        while ((br.readLine()) != null) {
            String[] row = line.split("/");
            for (String g : row) {
                System.out.println(g);

            }
        }
        br.close();

CodePudding user response:

Not a very efficient solution, but line reading with better APIs:

Path path = Paths.get("file1.txt");
try (Stream<String> in = Files.lines(path, Charset.defaultCharset())) {
    in.forEach(line -> {
            line = line.replaceFirst("/.*$", "");
            String[] fields = line.split(",");
            if (fields.length >= 5) {
                System.out.printf("Field 3: %s%n", field[2]);
            }
        });
}

It seams that / is ending lines with all columns.

CodePudding user response:

Here is one way of performing the various functions you are looking for - reading the file, removing the trailing "/", filtering by the first column or/and filtering by fourth column, and then writing the filtered lines to an output list and a file.

The code uses Java Streams and java.nio.file APIs and requres Java SE 8.

List<String> resultList = Files.lines(Paths.get("csv_data_in.txt"))
    .map(line -> line.replace("/", ""))
    .map(line -> line.split(","))
    .filter(arr -> arr[0].equals("06") && arr[3].equals("333"))
    .map(arr -> Stream.of(arr).collect(Collectors.joining(",")))
    .collect(Collectors.toList());
  
Files.write(Paths.get("csv_data_out.txt"), resultList);
  • Related