You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在终端编译运行含Jar包与TXT文件的Java项目及排障

Fixing the FileNotFoundException When Running Your Java Project from Terminal

Hey Anna, let's break down why your code works smoothly in the IDE but throws a file-not-found error when running from the terminal, and walk through simple fixes to get it working.

What's Causing the Error?

The Exception in thread "main" java.io.FileNotFoundException: src/out.txt (No such file or directory) issue comes down to mismatched relative file paths:

  • When you run java -cp .:jsoup-1.11.3.jar Main from the src directory, your program's working directory is set to src.
  • But your Writer class is trying to access src/out.txt—this means the program is actually looking for src/src/out.txt (since paths are relative to the current working directory), which doesn't exist. That's where the error originates.

Solutions to Try

1. Run the Program from the Correct Working Directory

The easiest fix is to navigate back to your Task_3 directory (the parent folder of src) and run the command from there. This way, the relative path src/out.txt will point to the actual file location:

# First go back to the Task_3 directory, then run:
java -cp src:lib/jsoup-1.11.3.jar Main
  • -cp src:lib/jsoup-1.11.3.jar tells Java to look for compiled classes in the src directory and include the jsoup jar from the lib folder.

2. Adjust the File Path in Your Code

If you prefer to run the program directly from the src directory, modify the file path in your Writer class to target the file without the src/ prefix:

// Update your path-related code to this:
String fs = System.getProperty("file.separator");
String filePath = "out.txt"; // This targets out.txt in your current working directory

Now when you run from src, the program will create or read out.txt directly in that folder, eliminating path confusion.

Bonus: Clean Up Compiled File Organization

Your current compile command places .class files right alongside your .java source files in src. For a more standard, organized setup, specify an output directory (like bin) when compiling:

# Run this from the Task_3 directory:
javac -cp lib/*.jar -d bin src/*.java

Then run the program using:

java -cp bin:lib/jsoup-1.11.3.jar Main

This keeps your source code and compiled classes separate, which is a common best practice for Java projects.


内容的提问来源于stack exchange,提问作者Anna F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:54:14