我正在将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;
}
答案 0 :(得分:1)
CSVParser parserr = CSVParser.parse(is, StandardCharsets.US_ASCII,
CSVFormat.EXCEL.withHeader());
好的,我创建了它。谢谢 !
答案 1 :(得分:0)
在spring-boot中工作,我编写了这段代码。
public void some(final MultipartFile file) {
...
Reader reader = new InputStreamReader(file.getInputStream());
CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
...
}
用于阅读csv的库:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
</dependency>