Alp*_*dız 3 java csv spring spring-boot
我将 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;
}
Run Code Online (Sandbox Code Playgroud)
在spring-boot上工作,我写了这段代码。
public void some(final MultipartFile file) {
...
Reader reader = new InputStreamReader(file.getInputStream());
CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
...
}
Run Code Online (Sandbox Code Playgroud)
用于读取csv 的库:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
CSVParser parserr = CSVParser.parse(is, StandardCharsets.US_ASCII,
CSVFormat.EXCEL.withHeader());
Run Code Online (Sandbox Code Playgroud)
好吧,我创立了它。谢谢 !
| 归档时间: |
|
| 查看次数: |
7514 次 |
| 最近记录: |