简体   繁体   English

java在netbeans中哪里寻找文件? 是否可以更改目录?

[英]where does java look for files in netbeans? And is it possible to change the directory?

So, I've got some txt files that I want to place in the following folder: src/test/resources/__files 因此,我将一些txt文件放置在以下文件夹中: src/test/resources/__files

However, when I run my project, I find that the compiler is looking for files in the project folder. 但是,当我运行项目时,我发现编译器正在项目文件夹中寻找文件。 Is there anyway of changing this as it becomes problematic when I try to create a JAR file - those files are then needed to be manually added to the target folder. 无论如何,是否有必要更改它,因为当我尝试创建JAR文件时会遇到问题-然后需要将这些文件手动添加到目标文件夹。

Thanks 谢谢

Since you are already placing your resource files in the src/test/resources folder, Maven should make them available on the classpath at runtime. 由于您已经将资源文件放置在src/test/resources文件夹中,因此Maven应该在运行时使它们在类路径上可用。 In this case, they should be on the classpath in your test build. 在这种情况下,它们应位于测试版本中的类路径上。 You may try the following code: 您可以尝试以下代码:

String fileName = "somefile.txt";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());

The Mkyong site does a good job of explaining how resources work in Maven. Mkyong站点很好地解释了Maven中资源的工作方式。

You seem to be working with the maven build tool, with per convention src/main/java, src/main/resources and for unit tests src/test/java and src/test/resources. 您似乎正在使用Maven构建工具,按照约定使用src / main / java,src / main / resources以及进行单元测试src / test / java和src / test / resources。

And then the files are not real file system File, but resources, packaged possibly in a jar (as you said): case-sensitive, / path separator and read-only InputStream. 然后这些文件不是真正的文件系统File,而是可能打包在jar中的资源(如您所说):区分大小写, /路径分隔符和只读InputStream。

You could keep the file as resource (under /src/main/resources/ then), and use that file as template for a real File, at the application System.getProperty("user.dir") (working directory), or System.getProperty("user.home") (home directory), see System Properties . 您可以将该文件保留为资源(在/ src / main / resources /下),然后将该文件用作真实文件的模板,位于应用程序System.getProperty("user.dir") (工作目录)或System.getProperty("user.home") (主目录),请参阅系统属性

InputStream in = .... .class.getResourceAsStream("___files/xyz.txt");

Or you could in maven copy from your own location to the target/distribution directory. 或者,您可以在maven中从您自己的位置复制到target / distribution目录。

我在Windows上使用NetBeans,我写String url = "src\\\\test\\\\resources\\\\__files"文件夹结构ProjFolder\\src\\test\\resources\\__files

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM