简体   繁体   中英

Reading from csv adds whitespace that can't be removed Java

I am reading from a csv file of people, starting with their id, name, and date they joined the application. When reading the first row, the first index adds a whitespace to the string. I am unable to remove this whitespace, as I want to parse it to an integer.

File nameOfFile = fileName;

    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {
        br = new BufferedReader(new FileReader(nameOfFile));
        while ((line = br.readLine()) != null) {

            String[] row = line.split(cvsSplitBy);

            temp = row[0].trim();
            temp.replaceAll("^\\s", "");
        //     temp.replaceAll(" ", "");
       //     String.format("%03d", temp);

            System.out.println(temp.length() + " " + temp + " "  + temp.charAt(0));

            age = Integer.parseInt(temp);

            name = row[1];
            dateJoined = row[2];



        }

    } catch (FileNotFoundException | ArrayIndexOutOfBoundsException exception) {

        System.out.println("File is not found, please try again.");
        System.out.println(exception);

    }

    if (br != null) {
        br.close(); //close buffered reader
    }

My csv file:

4 John 10/10/2010

5 Charles 24/08/2010

6 Andrew 09/01/2011

The System.out.println(temp.length() + " " + temp + " " + temp.charAt(0)); prints this:

2 4

1 5 5

1 6 6

where this System.out.println(temp.length() + " " + temp + " " + temp.charAt(1)); prints out:

2 4 4

Don't reinvent the wheel. I would use the Univocity parser and then map. More info at: https://www.univocity.com/pages/parsers-documentation Something along this (did not test it);

CsvParserSettings settings = new CsvParserSettings();
CsvParser parser = new CsvParser(settings);
List<String[]> allRows = parser.parseAll(new FileReader(yourfile));
List<Person> persons = allRows.stream().map(p->new Person(p[0],p[1],p[2])).collect(Collectors.toList())

In the Person bean I would make specific setMethods, such as:

public void setAge(String age2parse){
try{
this.age = Integer.parse(age2parse.replaceAll("[^\\d.]",""))
}catch(Exception e){
}
}
public void setName(String name2parse){
this.name = name; // You could divide name here, if wanted.
}
public void setDate(String date2parse){
this.date = date2parse // I would parse it and store it as Date object.
}

Finnaly, a constructor in the bean;

public Person(String a, String n, String d){
setAge(a);
setName(n);
setDate(d);
}

To print:

persons.stream().forEachOrdered(p->System.out.println(p.getAge()+" "+p.getName()+" "+p.getDate()))

Note: There is even way to use BeanRowProcessors, which seem to fit well when you have more fields in the bean, so please, check the documentation on Univocity.

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