gpt4 book ai didi

java - 如何读取位于项目文件夹java中的文件

转载 作者:行者123 更新时间:2023-12-02 03:16:46 26 4
gpt4 key购买 nike

使用 eclipse,我在名为 HackGSU 的项目文件夹中有一个名为 bad_words.txt 的文件。我想找到该文件并读取该文件的内容。我看到这个答案how to read text file relative path我尝试了这个:

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),它工作得很好,但是我怎样才能让程序读取该文件,这样如果我打包软件它仍然会找到正确的文件路径。

最佳答案

查看错误,您似乎没有获得完整路径。而不是

p.concat("/HackGSU/bad_words.txt");

尝试

p = p.concat("/HackGSU/bad_words.txt");

关于java - 如何读取位于项目文件夹java中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40191966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com