Java通配符导入失败,非通配符导入正常问题咨询
Hey there, let's break down why you're hitting that "bad source file" error and fix it step by step! The core problem here is a mismatch between your package declarations and directory structure, plus missing compile-time flags that help the compiler find your classes.
What's Going Wrong?
- Incorrect Source File Placement: Your
Foo.javaandBar.javadeclarepackage hoge.fuga;, but they're sitting directly in thesrc/directory. Java requires source files for a packagehoge.fugato live in asrc/hoge/fuga/subdirectory—this is how the compiler maps package names to file system paths. - Missing Compilation Context: You're not telling the compiler where to output compiled class files or where to look for existing classes, so it can't resolve the
hoge.fugapackage properly.
Step-by-Step Fix
1. Fix Your Directory Structure
Move Foo.java and Bar.java into the correct subdirectory under src/. Your final structure should look like this:
+ src/ - Senario.java // Rename to match your class name (capital S—Java is case-sensitive!) + hoge/ + fuga/ - Foo.java // package hoge.fuga; - Bar.java // package hoge.fuga; + hoge/ + fuga/ - Foo.class - Bar.class
Pro tip: Windows might ignore filename case, but Java doesn't—keeping filenames matching class names avoids cross-platform headaches later.
2. Compile the hoge.fuga Package Classes
Open Command Prompt, navigate to the src/ directory, and run this command:
javac -d .. hoge/fuga/Foo.java hoge/fuga/Bar.java
- The
-d ..flag tells the compiler to output compiled.classfiles to the parent directory (matching your existinghoge/fuga/structure outsidesrc/).
3. Compile Senario.java
Still in the src/ directory, run this command to compile your main class:
javac -cp .. Senario.java
- The
-cp ..flag adds the parent directory to the classpath, so the compiler can find thehoge.fugapackage classes you just compiled.
Test It Out
After compiling, you can run your class with:
java -cp .. Senario
This should resolve the imports and run without errors!
内容的提问来源于stack exchange,提问作者mogami74

