我有一个简单的Java Spring IO项目,其中的一个类应该从csv文件读取,对于每个读取的记录,参数都存储在帐户对象列表中。 我正在使用Force IDE Luna,并且读取文件的Class CsvAccountDao与xml文件的第一个bean中定义的csv文件位于同一包中。 xml文件也位于同一软件包下。 这是Bean文件:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
class="com.springinpractice.ch01.model.dao.csv.CsvAccountDao">
class="com.springinpractice.ch01.service.AccountService">
这是类文件CscAccountDao:
package com.springinpractice.ch01.model.dao.csv;
import java.io.BufferedReader;
import java.io.FileReader;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.core.io.Resource;
import com.springinpractice.ch01.model.Account;
import com.springinpractice.ch01.model.dao.AccountDao;
public class CsvAccountDao implements AccountDao {
private Resource csvResource;
public CsvAccountDao() {
// TODO Auto-generated constructor stub
}
public void setCsvResource(Resource csvFile){
this.csvResource = csvFile;
}
@Override
public List findAll() throws Exception {
List results = new ArrayList();
DateFormat fmt = new SimpleDateFormat("MMddyyyy");
BufferedReader br = new BufferedReader(
new FileReader(csvResource.getFile()));
String line;
while((line = br.readLine()) != null){
String[] fields = line.split(",");
String accountNo = fields[0];
BigDecimal balance = new BigDecimal(fields[1]);
Date lastPaidOn = fmt.parse(fields[2]);
Account account =
new Account(accountNo, balance, lastPaidOn);
results.add(account);
}
br.close();
return results;
}
}
请注意,方法setCsvResource将csv文件分配给资源对象的位置是异常问题开始的地方。 我在堆栈跟踪中得到一个异常错误,指出:
Jun 20, 2015 7:59:42 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@177e4b0: defining beans [accountDao,accountService]; root of factory hierarchy
Exception in thread "main" java.io.FileNotFoundException: class path resource [accounts.csv] cannot be resolved to URL because it does not exist
问)是否存在问题,我必须通过添加完整路径来更新第一个bean使用accounts.csv的XML文件? 由于class,xml和csv文件都在同一个包中,所以我认为不需要更具体。