简体   繁体   中英

FileNotFoundException - Reading a text file in java

I'm getting a file not found exception from this code even though it's within the try catch statement and I'm not sure what's wrong, the file is within the project folder and is called 'someFile.txt'. This is the main method:

public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("no arguments given");
        return;
    }
    double FRE = sortFile(args[0]);
    System.out.println("Readability of file " + args[0] + "= " + FRE);

}

And this is the sortFile method where the exception occurs:

public static double sortFile(String FileName) {
    int nWords = 0;
    int nSyllables = 0;
    int nSentences = 0;
    File text = new File(FileName);
    try {
        Scanner sc = new Scanner(text);
        while (sc.hasNext()) {
            contents.add(sc.next());
            ++nWords;
        }
        sc.close();
        for (String e : contents) {
            getNumSyllables(e);
        }

    } catch (FileNotFoundException e) {
        System.out.println("The file" + FileName + "could not be opened.");
        e.printStackTrace();
    }
    double FRE = getFRE(nWords, nSyllables, nSentences);
    return FRE;
}

Thanks for any help :)

well, the file does not exist in that location. Try to add

System.out.println(text.getAbsolutePath())

to see where the file is expected. Note, when you provide a relative path (eg some/path/filename.ext ), this is relative to the working directory. The working directory is the folder your java program is started in.

If you're using an IDE (eg Eclipse, IntelliJ, Netbeans) you can define the working directory in your run configuration.

See:

I'm getting a file not found exception from this code even though it's within the try catch statement

The try-catch does not prevent the Exception from being thrown. It merely executes the code in the catch block when an Exception is thrown, and you are just printing the stack trace in the catch block, which is what usually printed anyways on uncaught exceptions.

To resolve your actual issue, first try passing the full path to the file, verify that it works and then use Tim's answer to debug your absolute path.

尝试使用绝对路径启动程序。

java yourclassname absolutepath_to_someFile.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM