【问题标题】:How to give MultiPartfile to Reader in Java?如何在 Java 中将 MultiPartfile 提供给 Reader?
【发布时间】:2019-01-05 00:59:43
【问题描述】:

我将 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;
    }

【问题讨论】:

  • 它把 NPE 扔到哪里去了?你能提供一个堆栈跟踪吗?
  • 2018-07-28 00:45:56.274 WARN 2960 --- [nio-8080-exec-9] .mmaExceptionHandlerExceptionResolver :由处理程序执行引起的已解决异常:我认为 java.lang.NullPointerException就在这里,无法读取文件Reader in = new InputStreamReader(BankAccount.class.getClassLoader() .getResourceAsStream(file.getOriginalFilename()));
  • 是否可以给文件本身而不是文件名?
  • BankAccount.class.getClassLoader().getResourceAsStream 查找与您的应用程序捆绑在一起的资源(在 .jar 或 .war 中)。如果用户提交文件,您的应用程序不太可能与内部路径与提交文件完全匹配的资源捆绑。
  • 是的,你完全正确!我找到了解决方案。感谢您的评论。

标签: java spring csv spring-boot


【解决方案1】:

上工作,我编写了这段代码。

public void some(final MultipartFile file) {
  ...
  Reader reader = new InputStreamReader(file.getInputStream());
  CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
  ...
}

阅读库:

<dependency>
  <groupId>com.opencsv</groupId>
  <artifactId>opencsv</artifactId>
  <version>4.4</version>
</dependency>

【讨论】:

    【解决方案2】:
    CSVParser parserr = CSVParser.parse(is, StandardCharsets.US_ASCII,
                CSVFormat.EXCEL.withHeader());
    

    好的,我创建了它。谢谢 !

    【讨论】:

    • 嘿伙计。谢谢您的帮助!您应该将此标记为正确答案。
    猜你喜欢
    • 2012-03-27
    • 2020-08-13
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多