I am passing MultiPartFile as a parameter to my function and read with CSVFormat, but it gives me null pointer exception here is my code.
I want to read from file and assign that values to my objects. My CSV file like this:
Sender account,Receiver Account,Amount,Date
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;
}
Working on spring-boot, I wrote this fragment of code.
public void some(final MultipartFile file) {
...
Reader reader = new InputStreamReader(file.getInputStream());
CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
...
}
Library for read the csv:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
</dependency>
CSVParser parserr = CSVParser.parse(is, StandardCharsets.US_ASCII,
CSVFormat.EXCEL.withHeader());
Okay I founded it. Thanks !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With