0

I have this below file format csv format how i want to read is in the first iteration I need

id 701
tenant_id 5c33blahblah
attr_name Cadence
attr_title Cadence
description nana
is_enabled 1
is_active 1
created_at #####
updated_at NULL
created_by LSNOPQA
updated_by NULL
entity_type PROCESS
is_custom 1

and in the second iteration it has to fetch value from the third column i.e id at 700

  • Does this answer your question? [Parsing .csv file using Java 8 Stream](https://stackoverflow.com/questions/49660669/parsing-csv-file-using-java-8-stream) – pringi Feb 21 '22 at 12:11
  • here I don't have to give the column name without giving column name in a loop i need to get header values like 701,etc – Tirumalesh Y Feb 21 '22 at 12:18

1 Answers1

0

Open the file and read line by line. Then you can split the line at a specific character, in your example at a whitespace. And since you want to access the data at a later point you can put the String Arrays from your split into a list.

    public static void main(String[] args) {
        File csvFile = new File("path/to/file");
        List<String[]> results = new ArrayList<>();
        try(BufferedReader reader = new BufferedReader(new FileReader(csvFile))) {
            String line;
            while((line = reader.readLine()) != null) {
                results.add(line.split(" "));
            }
        } catch (IOException e) {

        }
    }

To make it a little bit more convenient you should use a POJO (Plain-Old-Java-Object)

public class CsvEntry {
    private String parameterName;
    private String parameterValue;

    public CsvEntry(String parameterName, String parameterValue) {
        this.parameterName = parameterName;
        this.parameterValue = parameterValue;
    }
}
    public static void main(String[] args) {
        File csvFile = new File("path/to/file");
        List<CsvEntry> results = new ArrayList<>();
        try(BufferedReader reader = new BufferedReader(new FileReader(csvFile))) {
            String line;
            while((line = reader.readLine()) != null) {
                String[] split = line.split(" ");
                results.add(new CsvEntry(split[0], split[1]));
            }
        } catch (IOException e) {

        }
    }

If you want to use the Java 8 way, this would be an example.

    public static void main(String[] args) {
        List<CsvEntry> results = new ArrayList<>();
        try {
            results = Files.lines(Path.of("path/to/file"))
                    .map(line -> line.split(" "))
                    .map(split -> new CsvEntry(split[0], split[1]))
                    .collect(Collectors.toList());
        } catch (IOException e) {
            
        }
    }

To use your transformed data, access the entry via index:

results.get(700)
RatzzFatzz
  • 144
  • 1
  • 7