用Java读取csv文件

时间:2013-04-17 04:47:24

标签: java regex csv

我有一个csv,我试图读入一个对象数组。我一直收到以下错误... java.util.InputMismatchException我认为这是因为它读取文件由空格而不是逗号分割。我相信我需要使用String.split()方法,但我不确定如何做到这一点。有什么建议。这是我到目前为止的代码......

public class Prog7
{
public static void main(String[] args)
{
    Part[] parts;
    int numParts;
    int partNumber;
    String description;
    double price;
    int quantity;
    String city;

    parts = new Part[100];
    numParts = 0;

    Scanner inFile = null;

    /*
     * open file
     */
    try
    {
        inFile = new Scanner( new File( "C:/COSC 210/Assignment#7/parts.txt" ) );
    }
    catch ( FileNotFoundException e )
    {
        System.err.println( "Error: file not found" );
    }

    inFile.useDelimiter(",");
    while( inFile.hasNext() )
    {
        partNumber = inFile.nextInt();
        description = inFile.next();
        price = inFile.nextDouble();
        city = inFile.next();
        quantity = inFile.nextInt();

        Part p = new Part(partNumber, description, price, 
                  quantity, city);
        parts[numParts]= p;
        numParts++;
    }
    inFile.close();

    for (int i = 0; i < numParts; i++)
    {
        System.out.println(parts[i].getPartNumber());
    }
}
}

3 个答案:

答案 0 :(得分:0)

您需要将数据读作String而不是int/double。读取数据后String将其解析为int

答案 1 :(得分:0)

如果粘贴导致此失败的文本行,将会有所帮助。如您所料,可能是空格字符在分隔符号前面或后面。只需将分隔符更改为

即可
inFile.useDelimiter("\\s*,\\s*")

答案 2 :(得分:0)

在你的位置我创建了单独的bean类

public class MyNewBean {

    int numParts;
    int partNumber;
    String description;
    double price;
    int quantity;
    String city;

    //get, set
}

结束然后阅读有关OpenCSV的优点。如果您使用逗号作为delimenter,您应该如何处理描述,其中也可以包含逗号。基于CSV文件中字段位置的Java bean

 CSVReader reader = new CSVReader(new FileReader("C:/COSC210/Assignment#7/parts.txt"));
ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy(); 
strat.setType(MyNewBean.class); 
String[] columns = new String[] {"numParts", "partNumber", "description", "price",                  "quantity", "city"}; // the fields to bind do in your JavaBean 
strat.setColumnMapping(columns); 
CsvToBean csv = new CsvToBean(); 
List list = csv.parse(strat, yourReader);

详细了解OpenCSV