Java Spring - 如何使用classpath指定文件位置? [英] Java Spring - How to use classpath to specify a file location?
问题描述
如何使用类路径指定Spring项目中文件的位置?
How can I use the classpath to specify the location of a file that is within my Spring project?
这就是我目前所拥有的:
This is what I have currently:
FileReader fr = new FileReader("C:\\Users\\Corey\\Desktop\\storedProcedures.sql");
这是硬编码到我的桌面。我想要的是能够使用我的项目中的文件的路径。
This is hardcoded to my Desktop. What I would like is to be able to use the path to the file that is in my project.
FileReader fr = new FileReader("/src/main/resources/storedProcedures.sql");
有什么建议吗?
推荐答案
我们是在谈论标准的 java.io.FileReader
?不行,但没有它就不会有用。
Are we talking about standard java.io.FileReader
? Won't work, but it's not hard without it.
/ src / main / resources
maven目录内容是放置在CLASSPATH的根目录中,因此您只需使用以下命令检索它:
/src/main/resources
maven directory contents are placed in the root of your CLASSPATH, so you can simply retrieve it using:
InputStream is = getClass().getResourceAsStream("/storedProcedures.sql");
如果结果不是 null
(资源未找到),随意将其包装在阅读器中:
If the result is not null
(resource not found), feel free to wrap it in a reader:
Reader reader = new InputStreamReader(is);
这篇关于Java Spring - 如何使用classpath指定文件位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!