IntelliJ IDEA中如何仅通过文件名而非绝对路径读取文件?
问题解答
核心原因
直接使用Paths.get("recipe.txt")时,JVM的相对路径基准是项目的根目录(即Restaurant文件夹),而非你的Main类所在的src/food/包目录。你的文件实际在src/food/下,JVM在项目根目录查找自然找不到。
解决方法
方法1:使用类加载器读取(推荐,适配IDE和JAR包运行)
因为recipe.txt属于类路径资源,用当前类的类加载器可以直接从包目录读取,编译后文件会被同步到classpath对应位置,打包成JAR后也能正常访问:
try (InputStream is = Main.class.getResourceAsStream("recipe.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is))) { br.lines().forEach(System.out::println); } catch (Exception e) { System.out.println("Error file: " + e.getMessage()); }
方法2:使用项目根目录相对路径(仅适合IDE开发阶段)
如果你坚持用Files.lines,可以指定相对于项目根目录的完整相对路径:
try { Files.lines(Paths.get("src/food/recipe.txt")) .forEach(System.out::println); } catch (Exception e) { System.out.println("Error file: " + e.getMessage()); }
注意:这种方式依赖开发时的目录结构,项目打包成JAR后src目录会消失,无法正常工作。
方法3:验证当前工作目录(排查用)
可以打印JVM的当前工作目录,确认相对路径基准:
System.out.println("Current working directory: " + System.getProperty("user.dir"));
运行后你会看到输出是项目根目录(比如C:\Users\Kevin\IdeaProjects\Restaurant),这也能解释为什么直接用文件名找不到文件。
内容的提问来源于stack exchange,提问作者Jay Money
相关产品推荐
相关产品推荐

