使用eclipse,我在名为HackGSU的项目文件夹中有一个名为bad_words.txt的文件。我想找到文件并读取文件的内容。我看到了这个答案,如何读取文本文件的相对路径,我尝试了这个:
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)
我也这样回答:如何使用Java直接从Internet读取文本文件?,但URL构造函数有问题。
如果我放置本地文件路径(C://.../bad_words.txt),就可以正常工作,但是如何获取程序来读取文件,以便如果我打包软件,它仍然可以找到正确的文件小路。
查看错误看起来好像没有完整的路径。代替
p.concat("/HackGSU/bad_words.txt");
尝试
p = p.concat("/HackGSU/bad_words.txt");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句