【问题标题】:How to pass the relative file path of a file in the src/main/resource folder of a Spring Boot webapp?如何传递 Spring Boot webapp 的 src/main/resource 文件夹中文件的相对文件路径?
【发布时间】:2020-05-13 14:11:29
【问题描述】:

我正在尝试访问资源文件夹中的特定文件,获取该 uri,将其转换为 toString,然后使用该文件通过 ftp 将该文件发送到服务器。下面是我目前用来尝试的代码,但我不断收到 FileNotFoundException。如果有人能告诉我我做错了什么,或者提供另一种方法来做到这一点,那就太好了!

@Value("classpath:submitTest.txt")
private Resource res;

private String submitJcl(FTPClient ftp, String serverName) throws IOException {

    FileInputStream inputStream = new FileInputStream(res.getURI().toString());
    ftp.storeFile(serverName, inputStream);  

    return result;
}

错误:

2020-05-13 09:04:25.353 ERROR 11472 --- [nio-8443-exec-3] c.cat.pis.service.CnlLetterServiceImpl   : java.io.FileNotFoundException: file:\C:\Users\mallid2\eclipse-new-PIS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Product%20Information%20System%20(PIS)\WEB-INF\classes\submitTest.txt (The filename, directory name, or volume label syntax is incorrect)

【问题讨论】:

    标签: java spring-boot file ftp


    【解决方案1】:

    您可以使用 getClass().getClassLoader().getResource() 从 Resource 文件夹中获取文件,例如

    File file = new File(getClass().getClassLoader().getResource("submitTest.txt").getFile();
    

    或者,如果您需要 inputStream,那么您可以使用:

    InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("submitTest.txt");
    

    希望这会有所帮助。

    【讨论】:

    • 是的,inputStream 正是我想要的。它完美地工作。谢谢!
    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多