Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give MultiPartfile to Reader in Java?

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;
    }
like image 242
Alpcan Yıldız Avatar asked May 10 '26 10:05

Alpcan Yıldız


2 Answers

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>
like image 106
Harold Castillo Avatar answered May 13 '26 01:05

Harold Castillo


CSVParser parserr = CSVParser.parse(is, StandardCharsets.US_ASCII,
            CSVFormat.EXCEL.withHeader());

Okay I founded it. Thanks !

like image 26
Alpcan Yıldız Avatar answered May 13 '26 01:05

Alpcan Yıldız