使用eclipse,我的項目文件夾中標題爲bad_words.txt的文件名爲HackGSU。我想找到該文件並閱讀該文件的內容。我看到這個答案how to read text file relative path,我想這:如何讀取位於項目文件夾中的文件java
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() {
p.concat("/HackGSU/bad_words.txt");
//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) {
e.printStackTrace();
}
}
}
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return words;
}
但我收到此回溯:
java.io.FileNotFoundException: C:\Users\nbrow_000\workspaceProjects\HackGSU (Access is denied)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at gsu.hack.harassment.BadWords.openFile(BadWords.java:28)
at gsu.hack.harassment.HarassFilter.<clinit>(HarassFilter.java:10)
at gsu.hack.harassment.CheckPercentage.main(CheckPercentage.java:20)
Exception in thread "main" java.lang.NullPointerException
at gsu.hack.harassment.HarassFilter.checkHarass(HarassFilter.java:23)
at gsu.hack.harassment.CheckPercentage.main(CheckPercentage.java:20)
我也因此這個答案How to read a text file directly from Internet using Java?,但我曾與URL構造一個問題。
如果我把本地文件路徑(C://.../bad_words.txt)它工作得很好,但我怎樣才能讓程序讀取文件,如果我打包軟件它仍然會找到適當的文件路徑。
改爲'HackGSU/bad_words.txt' – emotionlessbananas
'HackGSU'是項目的文件夾嗎?或其中的子文件夾? – c0der
'p.concat(「/ HackGSU/bad_words.txt」)'不會像你可能除外。字符串是不可變的。 'concat'不會將某些內容添加到'p',但會返回一個新的String。更改爲'p + =「/ HackGSU/bad_words.txt」' –