如何传递 Spring Boot webapp 的 src/main/resource 文件夹中文件的相对文件路径?

How to pass the relative file path of a file in the src/main/resource folder of a Spring Boot webapp?

我正在尝试访问资源文件夹中的特定文件,获取该 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)

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

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

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

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

希望对您有所帮助。