如何在终端编译运行含Jar包与TXT文件的Java项目及排障
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 Mainfrom thesrcdirectory, your program's working directory is set tosrc. - But your Writer class is trying to access
src/out.txt—this means the program is actually looking forsrc/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.jartells Java to look for compiled classes in thesrcdirectory and include the jsoup jar from thelibfolder.
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

