Java 1.如何逐行读取csv文件中的数据,以及如何验证csv文件中的特定行

Java 1.如何逐行读取csv文件中的数据,以及如何验证csv文件中的特定行,java,Java,比如说 s_id、姓名、年龄: 2、30: 所以我想确认一下年龄。这意味着年龄应该在15到60岁之间。它应该始终是整数。它不能是浮动的或任何其他的 public class Customer { private String customerId; private String companyName; // ... public static Customer create(final String... args) { if (args.length != 15) {

比如说 s_id、姓名、年龄: 2、30:

所以我想确认一下年龄。这意味着年龄应该在15到60岁之间。它应该始终是整数。它不能是浮动的或任何其他的

public class Customer {
private String customerId;
private String companyName;

// ...
public static Customer create(final String... args) {
    if (args.length != 15) {
        return null; // or throw an exception
    }
    final Customer rv = new Customer();
    rv.setCustomerId(args[0]);
    rv.setCompanyName(args[1]);
    // ...
    return rv;
}

public String getCustomerId() {
    return customerId;
}

public void setCustomerId(final String customerId) {
    this.customerId = customerId;
}

public String getCompanyName() {
    return companyName;
}

public void setCompanyName(final String companyName) {
    this.companyName = companyName;
}
}

ad 1如何在csv文件中逐行读取数据

    Customer c1 = new Customer(); 
    try {
        InputStream ips = new FileInputStream("input.txt");
        InputStreamReader ipsr = new InputStreamReader(ips);
        BufferedReader br = new BufferedReader(ipsr);
        String line;
        while ((line = br.readLine()) != null) {
            String[] s = line.split(",");
            c1.setCustomerId(s[0]);
            c1.setCompanyName(s[1]);
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
ad 2如何验证csv中的一个paricular行

public void setCustomerId(final String customerId) throws IllegalArgumentException {

    if (customerId != null && customerId != "") {
        int temp = Integer.parseInt(customerId);
        if (temp < 15 || temp > 60) {
            throw new IllegalArgumentException("Invalid age");
        }
    }
    this.customerId = customerId;
}

您可以使用CSV阅读器读取任何.CSV文件

有一些方法可以直接获取CSV文件中的一行

您可以直接使用java IO流读取CSV文件

比如说,

    BufferedReader br = new BufferedReader(new FileReader(csvFile));
    while ((line = br.readLine()) != null) {
            // use comma as separator
        String[] emp = line.split(",");
        System.out.println("S_Id" + emp[0] 
                             + " , name=" + emp[1] + ", age="+emp[2]);
                 // You can validate your age here.....
    }

her是一个使用

首先,我将使用customer类和customer.csv来帮助您执行主类

public class Customer {
    private String  id;
    private String name;
    private int age;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Customer other = (Customer) obj;
        if (age != other.age)
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Customer [id=");
        builder.append(id);
        builder.append(", name=");
        builder.append(name);
        builder.append(", age=");
        builder.append(age);
        builder.append("]");
        return builder.toString();
    }
}
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

public class ApacheCommonsCSVParser {

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

        //Create the CSVFormat object
        CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(',');

        //initialize the CSVParser object
        CSVParser parser = new CSVParser(new FileReader("customer.csv"), format);

        List<Customer> emps = new ArrayList<Customer>();
        for(CSVRecord record : parser){
            Customer emp = new Customer();
            emp.setId(record.get("s_id"));
            emp.setName(record.get("name"));
            emp.setAge(Integer.parseInt(record.get("age")));
            if(emp.getAge()>=15){
                emps.add(emp);
            }

        }
        //close the parser
        parser.close();

        System.out.println(emps);
    }
}
我在ApacheCommonsCSVParser类中使用的customer.csv

s_id,name,age
1,customer1,30
2,customer2,31
3,customer3,25
4,customer4,15
5,customer5,14
最后是ApacheCommonsCSVParser.javamain类

public class Customer {
    private String  id;
    private String name;
    private int age;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Customer other = (Customer) obj;
        if (age != other.age)
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Customer [id=");
        builder.append(id);
        builder.append(", name=");
        builder.append(name);
        builder.append(", age=");
        builder.append(age);
        builder.append("]");
        return builder.toString();
    }
}
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

public class ApacheCommonsCSVParser {

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

        //Create the CSVFormat object
        CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(',');

        //initialize the CSVParser object
        CSVParser parser = new CSVParser(new FileReader("customer.csv"), format);

        List<Customer> emps = new ArrayList<Customer>();
        for(CSVRecord record : parser){
            Customer emp = new Customer();
            emp.setId(record.get("s_id"));
            emp.setName(record.get("name"));
            emp.setAge(Integer.parseInt(record.get("age")));
            if(emp.getAge()>=15){
                emps.add(emp);
            }

        }
        //close the parser
        parser.close();

        System.out.println(emps);
    }
}

我只是想澄清一下。你是否可以从csv文件中读取?不要发明轮子。使用常用且经过测试的库,如Apache CSV解析器: