有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法获取该文件

我试图获取存储在本地系统中的文件,为此我编写了以下代码

我从数据库获得的原始路径是C:\Users\Admin\Documents\BulkmailExcelPath\1599203585103000000_4898E400.xlsx

如果我直接给出,那就是抛出错误。为此,我将\替换为\\。但我还是犯了同样的错误

            String path = individualObject.getAttchmentPath().replace("\\", "\\\\"); 
            System.out.println(path);
            FileSystemResource file = new FileSystemResource(path);



Exception in thread "Timer-0" java.nio.file.InvalidPathException: Trailing char < > at index 499: C:\Users\user\Documents\BulkmailExcelPath\attachments\1599205942697000000_log4j-application.log                                                                                                                                                                                                                                                                                                                                                                                                                    
    at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:191)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
    at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
    at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
    at java.io.File.toPath(File.java:2234)
    at org.springframework.core.io.FileSystemResource.<init>(FileSystemResource.java:82)
    at com.util.bulkmailer.service.BulkMailSender.sendSimpleMessage(BulkMailSender.java:54)
    at com.util.bulkmailer.processor.BulkMailProcessor.processor(BulkMailProcessor.java:247)
    at com.kcs.util.bulkmailer.controller.BulkMailerController.sendMail(BulkMailerController.java:109)
    at com.util.bulkmailer.controller.BulkMailerController$1.run(BulkMailerController.java:80)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)

如果我给出path变量中的字符串,那么它能够执行该行,并且不会给出任何错误。原因可能是什么


共 (2) 个答案

  1. # 1 楼答案

    根据错误消息,我猜测路径末尾包含无效的空格字符。可以使用路径对象而不是字符串来验证URI,如Path path = Paths.get(textPath);

  2. # 2 楼答案

    在路径的末尾有尾随空格。将第一行替换为:

    String path = individualObject.getAttchmentPath().replace("\\", "\\\\").trim();