简体   繁体   English

在 Intellij 中放置文本文件的位置

[英]Where to put text file in Intellij

I want to read file named FileofNames.txt in a code.我想在代码中读取名为 FileofNames.txt 的文件。 but when i run this code i am getting a NullPointerException.但是当我运行这段代码时,我得到了一个 NullPointerException。

URL url=ApacheCommonIOExample.class.getResource("src/Files/FileofNames.txt");
System.out.println(url.getPath());

So my question is that where can i put file in intellij so that i can read it from any java source code.所以我的问题是我可以将文件放在 intellij 的什么位置,以便我可以从任何 Java 源代码中读取它。 Image of my directory .Currently my text file is in src/Files and i want to read it from src/org/java.practice/FileName.java .我的目录的图像。目前我的文本文件在 src/Files 中,我想从 src/org/java.practice/FileName.java 读取它。

Assuming you are using the Maven Standard Directory Layout then resources should be placed in /src/main/resources (or /src/test/resources as appropriate).假设您使用的是Maven 标准目录布局,那么资源应放置在/src/main/resources (或/src/test/resources视情况而定)中。

Then loaded using Java code, something like this:然后使用Java代码加载,如下所示:

final InputStream stream = this.getClass().getResourceAsStream("/filename.txt");
final InputStreamReader reader = new InputStreamReader(stream);
final BufferedReader buffered = new BufferedReader(reader);
String line = buffered.readLine();

Explanation解释

getResource and getResourceAsStream will load the resource using the same classLoader used to load the context class. getResourcegetResourceAsStream将使用用于加载上下文类的相同 classLoader 加载资源。 In my example this class;在我的例子中this类; in your case the classLoader of ApacheCommonIOExample .在您的情况下是ApacheCommonIOExample的 classLoader 。 These may not be the same.这些可能不一样。 In my example the resource and class are known to be in the same place since that is how it was defined by the maven project and hence my mentioning of it.在我的示例中,已知资源和类位于同一位置,因为 maven 项目是这样定义的,因此我提到了它。 In your example it is likely to be trying to load the resource from the same location as it loaded ApacheCommonIOExample .在您的示例中,它可能会尝试从与加载ApacheCommonIOExample相同的位置加载资源。

When you make the jar, make sure to include the text file in the assembly.制作 jar 时,请确保在程序集中包含文本文件。

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

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