我将MultiPartFile作为参数传递给我的函数,并使用CSVFormat读取,但这里给了我一个空指针异常,以下是我的代码。
我想从文件中读取并将其值分配给我的对象。我的CSV文件如下:
发送方账户,接收方账户,金额,日期
123,654321,100,19-07-2018 12:13:00
public List<BankAccount> readCsv(MultipartFile file) throws IOException {
List<BankAccount> bankAccountList = new ArrayList<BankAccount>();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
Reader in = new InputStreamReader(BankAccount.class.getClassLoader()
.getResourceAsStream(file.getOriginalFilename()));
Iterable<CSVRecord> parser = CSVFormat.EXCEL.withHeader("Sender account","Receiver Account","Amount","Date").parse(in);
for (CSVRecord csvRecord : parser) {
BankAccount bankAccount = new BankAccount();
String senderAccount = csvRecord.get("Sender account");
String receiverAccount = csvRecord.get("Receiver account");
float amount = Float.parseFloat(csvRecord.get("Amount"));
ZonedDateTime date = LocalDateTime.parse(csvRecord.get("Date"), dtf)
.atZone(ZoneId.of("Asia/Istanbul"));
bankAccount.setFromId(senderAccount);
bankAccount.setToId(receiverAccount);
bankAccount.setDate(date);
bankAccount.setBalance(amount);
bankAccountList.add(bankAccount);
}
return bankAccountList;
}
BankAccount.class.getClassLoader().getResourceAsStream
寻找与您的应用程序捆绑在一起的资源(在 .jar 或 .war 中)。如果用户提交了一个文件,那么很不可能您的应用程序会捆绑一个内部路径完全匹配所提交文件的资源。 - VGR