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

标签 java io filepath filereader filenotfoundexception

使用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/63722693/

相关文章:

java - 无法在 apache tomcat 服务器上显示 json 格式的值

java - AtomicInteger 是同步原语吗?

c# - 在目录中按顺序对文件进行编号

xcode4 - 如何在XCode 4中将分组(本地化)文件的位置从绝对路径更改为相对路径?

ios - 文档目录中保存的文件名有空格字符

python - FileNotFoundError:[WinError 2]尝试使用pysndfx时,系统找不到指定的文件

java - Linux下Swing框架切换时白屏

java - 扩展泛型

python - 文件 i/o 和二进制模式的含义

c - 关闭 ARM9 (LPC3141) 上的单个 GPIO 引脚