Priyank Jain
Priyank Jain

Reputation: 787

Where to put text file in Intellij

I want to read file named FileofNames.txt in a code. but when i run this code i am getting a 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. 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 .

Upvotes: 5

Views: 8219

Answers (1)

Martin Spamer
Martin Spamer

Reputation: 5585

Assuming you are using the Maven Standard Directory Layout then resources should be placed in /src/main/resources (or /src/test/resources as appropriate).

Then loaded using Java code, something like this:

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. In my example this class; in your case the classLoader of ApacheCommonIOExample. 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. In your example it is likely to be trying to load the resource from the same location as it loaded ApacheCommonIOExample.

When you make the jar, make sure to include the text file in the assembly.

Upvotes: 6

Related Questions