0

我有一个 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());
    }
}
}
4

3 回答 3

0

在你的地方,我创建了单独的 bean 类

public class MyNewBean {

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

    //get, set
}

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

 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 的更多信息

于 2013-04-17T05:21:24.403 回答
0

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

于 2013-04-17T04:51:20.747 回答
0

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

inFile.useDelimiter("\\s*,\\s*")
于 2013-04-17T05:04:56.383 回答