Java NetBeans中HashMap读取文件遇FileNotFoundException问题排查
I wrote a Java program to count word frequencies using a HashMap, but I keep getting a FileNotFoundException when running it. I'm not sure if the file doesn't exist, or if there's an issue with how I'm handling the file path. Here's my code and the full error stack trace:
import java.io.File; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; public class WordFrequencies { @SuppressWarnings({"unchecked"}) public static void main(String[] args) throws Exception { String path = new File(".").getAbsolutePath(); path=path.substring(0, path.length() - 1); path+="alice.txt"; File file = new File(path); String filename = "alice.txt"; Map<String,Integer> frequencies = new HashMap<String,Integer>(); Scanner sc = new Scanner(new File(filename)); // This is the problematic line! while (sc.hasNext()) { String word = sc.next(); if (frequencies.containsKey(word)) { // increment the frequency count for this word by 1 frequencies.put(word,frequencies.get(word)+1); } else { // start the frequency count at 1 frequencies.put(word,1); } } System.out.println(frequencies); Set<Map.Entry<String,Integer>> entries = frequencies.entrySet(); Map.Entry<String,Integer> [] entryArray = entries.toArray(new Map.Entry[0]); Arrays.sort(entryArray, new Comparator<Map.Entry<String,Integer>>() { public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) { return o1.getKey().compareTo(o2.getKey()); } }); for (Map.Entry<String,Integer> entry : entryArray) System.out.println(entry); Arrays.sort(entryArray, new Comparator<Map.Entry<String,Integer>>() { public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<String,Integer> entryArray1 : entryArray) System.out.println(entryArray1); } }
Full exception trace:
Exception in thread "main" java.io.FileNotFoundException: alice.txt (The system cannot find the file specified) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.util.Scanner.<init>(Scanner.java:611) at fross_charles_pa.pkg9.WordFrequencies.main(WordFrequencies.java:30) C:\Users\lastname\AppData\Local\NetBeans\Cache\11.3\executor-snippets\run.xml:111: The following error occurred while executing this line: C:\Users\fross\AppData\Local\NetBeans\Cache\11.3\executor-snippets\run.xml:94: Java returned: 1 BUILD FAILED (total time: 7 seconds)
Let's break down the issue here:
The Root Cause
You spent time constructing an absolute path to alice.txt and creating a File object (file) using that path, but you never actually use that file object! Instead, you create a brand new File with just the filename "alice.txt", which uses the program's current working directory (not the path you built).
Java looks for files with relative paths (like just the filename) in the directory from which you run the program, which might not be where you placed alice.txt.
Fixes You Can Apply
1. Use the File object you already created
The simplest fix is to replace the problematic line with the file variable you built earlier:
Scanner sc = new Scanner(file);
This uses the absolute path you constructed, so it will look for the file exactly where you intended.
2. Verify your working directory
If you want to keep using the relative path, first check where your program is running from. Add this line at the start of main() to print the working directory:
System.out.println("Current working directory: " + System.getProperty("user.dir"));
Then place alice.txt directly in that directory, and your original code will work.
3. Use a hardcoded absolute path (quick test)
For testing purposes, you can also use a full absolute path to the file, like:
String filename = "C:/path/to/your/alice.txt"; // Windows example // or for macOS/Linux: "/home/yourname/alice.txt"
This avoids any confusion about relative paths, though it's less portable than using the dynamic path you originally built.
Bonus Tip
You can also add a check to see if the file exists before trying to read it, which helps with debugging:
if (!file.exists()) { System.err.println("File not found at: " + file.getAbsolutePath()); System.exit(1); }
This will print the exact path Java is looking for, so you can confirm if the file is really there.
内容的提问来源于stack exchange,提问作者DjMaxLETU

