How to compile Java files in subdirectories?

QuestionsQuestions8 SkillsProYour First Java LabNov, 14 2025
0235

To compile Java files located in subdirectories, you can use the javac command with the -d option to specify the destination for the compiled class files, along with the ** wildcard to include files from subdirectories. Here are a couple of methods to do this:

Method 1: Using Wildcards with -d

If you want to compile all Java files in the current directory and all its subdirectories, you can use the following command:

javac -d output_directory **/*.java
  • -d output_directory: This option specifies the directory where the compiled .class files will be placed. You can replace output_directory with your desired output folder.
  • **/*.java: This pattern matches all .java files in the current directory and all subdirectories.

Example

Assuming you have the following directory structure:

src/
├── Main.java
└── utils/
    ├── Helper.java
    └── HelperUtils.java

You can compile all Java files like this:

javac -d bin src/**/*.java

This command will compile all Java files in the src directory and its utils subdirectory, placing the compiled .class files in the bin directory.

Method 2: Compiling Each Subdirectory Manually

If you prefer to compile files in specific subdirectories, you can specify each subdirectory explicitly:

javac -d output_directory src/Main.java src/utils/Helper.java src/utils/HelperUtils.java

Note

Make sure that the output directory exists before running the command, as javac will not create it automatically. You can create it using the mkdir command if needed:

mkdir -p output_directory

This way, you can effectively compile Java files located in subdirectories.

0 Comments

no data
Be the first to share your comment!