
java程序默认从项目根目录(即user.dir)查找文件,而非源码目录(src),因此将words.txt放在src文件夹中无法被filereader("words.txt")直接定位。
java程序默认从项目根目录(即user.dir)查找文件,而非源码目录(src),因此将words.txt放在src文件夹中无法被filereader("words.txt")直接定位。
在Java中,使用相对路径(如"words.txt")构造FileReader时,JVM会以当前工作目录(Current Working Directory)为基准进行查找,该目录由系统属性user.dir决定,通常等于IDE中项目的根目录(例如:/Users/xxx/MyJavaProject),而不是src/子目录。
✅ 正确做法:定位并放置文件
首先确认当前工作目录:
System.out.println("Current working directory: " + System.getProperty("user.dir"));
运行后控制台将输出类似:
Current working directory: /path/to/your/project-root
请将words.txt直接放在该路径下(即项目根目录),而非src/内。例如:
MyJavaProject/ ├── words.txt ← 正确位置(与src同级) ├── src/ │ └── Aula12/ │ └── Ex1.java └── bin/ (or out/)
⚠️ 注意事项
- IDE行为差异:IntelliJ IDEA 默认以项目根目录为工作目录;Eclipse 通常也相同,但若配置了“Working directory”则可能不同(可在Run Configuration中检查)。
-
资源文件推荐方案:若需将文件随代码一起管理(如打包进JAR),应使用类路径加载:
InputStream is = Ex1.class.getClassLoader().getResourceAsStream("words.txt"); if (is == null) { throw new FileNotFoundException("words.txt not found in classpath"); } Scanner input = new Scanner(is, StandardCharsets.UTF_8);并确保words.txt置于src/main/resources/(Maven)或src/根下(非包内),使其被编译器复制到输出目录。
? 修复后的主逻辑(精简健壮版)
public static void main(String[] args) {
String filename = "words.txt";
System.out.println("Looking for file in: " + System.getProperty("user.dir"));
try (Scanner input = new Scanner(new FileReader(filename), StandardCharsets.UTF_8)) {
ArrayList<string> texto = new ArrayList();
while (input.hasNext()) {
texto.add(input.next());
}
long total = texto.size();
long unique = texto.stream().distinct().count();
System.out.println("Número total de palavras: " + total);
System.out.println("Número de palavras diferentes: " + unique);
} catch (FileNotFoundException e) {
System.err.println("❌ File not found: " + filename + " — please place it in: " + System.getProperty("user.dir"));
} catch (IOException e) {
System.err.println("❌ I/O error: " + e.getMessage());
}
}</string>
? 提示:使用try-with-resources自动关闭Scanner;显式指定字符集避免乱码;利用Stream API简化去重统计,提升可读性与健壮性。
总之,理解并主动确认user.dir是解决“文件找不到”问题的第一步,合理规划资源路径则是长期开发的可靠实践。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











