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

Java通配符导入失败,非通配符导入正常问题咨询

Fixing Java Package Compilation Error in Java 8 (Windows 7)

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?

  1. Incorrect Source File Placement: Your Foo.java and Bar.java declare package hoge.fuga;, but they're sitting directly in the src/ directory. Java requires source files for a package hoge.fuga to live in a src/hoge/fuga/ subdirectory—this is how the compiler maps package names to file system paths.
  2. 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.fuga package 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 .class files to the parent directory (matching your existing hoge/fuga/ structure outside src/).

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 the hoge.fuga package 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:08:18