Maven exec:java:如何在资源目录中打开和读取文件? [英] Maven exec:java : how to open and read a file in the resources directory?
问题描述
这是我项目的结构。
proj
---src
----main
----java
----Main.java
----resources
----res.txt
我在Eclipse中使用m2eclipse插件。
在Main.java中,我有
I am using m2eclipse plugin with Eclipse. In Main.java, I have
File f = new File("res.txt"); System.out.println(f.getAbsolutePath());
当我运行mvn exec:java时,打印出来的路径是... \ proj \res.txt。如何在... \ proj\target\classes目录中查找资源文件?
When I run mvn exec:java, the path got printed out is "...\proj\res.txt". How can I make it look for the resource file in "...\proj\target\classes" directory?
编辑:
感谢我原来问题的答案。我有一个后续问题:
Thanks for the answers to my original question. I have a follow-up questions:
所以基本上我想做的是让Main类读取res.txt然后生成一个新的newres .txt到资源目录,以便我可以在以后的包阶段将这个新的newres.txt打包到jar文件中。目前我将这个exec:java挂载到prepare-package阶段。如何在资源目录中创建这个newres.txt而没有硬编码的绝对路径或者取决于Maven的目录结构?
So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?
推荐答案
我想我会回答我自己的问题, Thread.currentThread()。getContextClassLoader()。getResourceAsStream()
对我来说效果最好,特别是当项目为另一个Web项目生成jar依赖项时。
I guess I will answer my own question, Thread.currentThread().getContextClassLoader().getResourceAsStream()
works the best for me, especially when the project produces a jar dependency for another web project.
这篇关于Maven exec:java:如何在资源目录中打开和读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!