如何将文件放在Java应用程序中,以便main和test都可以访问它?

时间:2014-10-01 20:29:36

标签: java

我有样式表文件(例如myStyle.xslt)。我正在尝试决定将此文件放在我的Web应用程序中的哪个位置,以便src和test都可以访问它。我在/src文件夹中的所有包中的源代码以及/test文件夹中的包中的测试代码。

1 个答案:

答案 0 :(得分:0)

我认为你使用Maven。

将文件放在src/main/resources/<your special place>/myStyle.xslt文件夹中。

在您的应用程序和测试中,您可以通过

访问该文件
// Get the Classloader to load the XSLT
ClassLoader classloader = this.getClass().getClassLoader();
// Get th URL of the file
URL url = classloader.getResource("<your special place>/myStyle.xslt");
// Now you can read it...
InputStream in = url.openStream();
// ...or use it as a file
// ATTATION: This works only if the file is not inside a a JAR, WAR etc.
//           But it works inside your JUnit or TestNG tests and in an exploded WAR
File file = new File(url.toURI());

希望有所帮助