Nate B Nate B - 3 years ago 213
Java Question

How to read a file that is located in the project folder java

Using eclipse, I have a file titled bad_words.txt in my project folder titled HackGSU. I want locate the file and read the contents of the file. I saw this answer how to read text file relative path and I tried this:

private static String words[][] = new String[3][];
private static int ok = 17 + 2; //Add two for comment & empty line in text file
private static int med = 26 + 2; //Add two for comment & empty line in text file
private static int bad = 430 + 1; //Add one for comment in text file
private static String p = new File("").getAbsolutePath();

public static String[][] openFile() {


//Set the a limit for the amount of words in each row
words[0] = new String[getOk()];
words[1] = new String[getMed()];
words[2] = new String[getBad()];

//Read the text file to add bad words to an array
try {
FileReader fr = new FileReader(p);
//Wrap file
BufferedReader br = new BufferedReader(fr);

//Add each line of file into the words array
for(int i = 0; i < words.length; i++) {

for(int j = 0; j < words[i].length; j++) {
try {
words[i][j] = br.readLine();
catch (IOException e) {

catch (FileNotFoundException e1) {

return words;

But I received this traceback: C:\Users\nbrow_000\workspaceProjects\HackGSU (Access is denied)
at Method)
at Source)
at<init>(Unknown Source)
at<init>(Unknown Source)
at<init>(Unknown Source)
at gsu.hack.harassment.BadWords.openFile(
at gsu.hack.harassment.HarassFilter.<clinit>(
at gsu.hack.harassment.CheckPercentage.main(

Exception in thread "main" java.lang.NullPointerException
at gsu.hack.harassment.HarassFilter.checkHarass(
at gsu.hack.harassment.CheckPercentage.main(

I also so this answer How to read a text file directly from Internet using Java?, but I had a problem with the URL constructor.

If I put the local file path (C://.../bad_words.txt) it works just fine, but how can I get the program to read the file so that if I package the software it will still find the proper file path.

Answer Source

Looking at the error it doesn't look like you are getting the full path. Instead of



p = p.concat("/HackGSU/bad_words.txt");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download