简体   繁体   English

读取Java中的CSV文件

[英]Reading a csv file in Java

I have a csv that I am trying to read into an array of objects. 我正在尝试将csv读入对象数组。 I keep getting the following error... java.util.InputMismatchException I think it is because its reading the file split by spaces and not by the commas. 我不断收到以下错误... java.util.InputMismatchException我认为这是因为它读取的文件是由空格而不是逗号分隔的。 I believe I need to use the String.split() method, but I am not sure exactly how to do this. 我相信我需要使用String.split()方法,但是我不确定到底该怎么做。 Any suggestions. 有什么建议么。 Here is the code that I have thus far... 这是我到目前为止的代码...

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

you need to read the data as String rather than int/double . 您需要将数据读取为String而不是int/double After reading data as String parse it to int . 在将数据读取为String解析为int

It would help if you paste the line of text that causes this failure. 如果您粘贴导致此失败的文本行,将会有所帮助。 As you suspect, probably a space char precedes or succeeds the delimited comma. 如您所怀疑,空格字符可能在定界逗号之前或之后。 Just change the delimiter to 只需将定界符更改为

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

In your place I create separate bean class 在您的地方,我创建了单独的bean类

public class MyNewBean {

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

    //get, set
}

End then read about advantages of OpenCSV. 然后结束阅读有关OpenCSV的优点。 If you use comma as delimenter what should you do with description which also can contain commas. 如果使用逗号作为分隔符,则应使用也可以包含逗号的描述做什么。 Java bean based on the field positions in your CSV file 基于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);

Read more about OpenCSV 进一步了解OpenCSV

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM