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

时间:2014-10-20 10:16:04

标签: 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) {
        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;
}
}

3 个答案:

答案 0 :(得分:0)

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中的特定行

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;
}

答案 1 :(得分:0)

您可以使用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.....
    }

答案 2 :(得分:0)

她是使用Commons CSV Api

从.csv文件中读取的示例

Fist我会,但客户类和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();
    }
}

我在ApacheCommonsCSVParser类中使用的customer.csv

s_id,name,age
1,customer1,30
2,customer2,31
3,customer3,25
4,customer4,15
5,customer5,14

最后是ApacheCommonsCSVParser.java(主类)

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);
    }
}