手动编译Android Studio项目时,如何用通配符打包仅含.class的.jar?
Hey there, I’ve run into this exact issue before when manually packaging Java projects—let’s get you sorted out! The problem with using *.class directly often boils down to how your shell handles wildcards or missing recursive support for subdirectories. Here are a few reliable solutions:
Solution 1: Target .class Files in the Current Directory (If They’re All There)
If all your compiled .class files are in your current working directory, run this command:
jar -cf Package.jar *.class
Note: If you get an error here, it’s likely because there are no
.classfiles in your current directory—double-check you’re in the right folder (usually something likebuild/classes/java/mainfor Android Studio projects). If your shell can’t expand*.class, it’ll pass the literal string tojar, which will throw an error because no file named*.classexists.
Solution 2: Recursively Package All .class Files (Including Subdirectories)
Android Studio projects often have .class files organized in subdirectories matching your package structure. Use find to locate all .class files and pass them to jar:
find . -name "*.class" -exec jar -cf Package.jar {} +
This command will:
- Search recursively from your current directory (
.) - Find every file ending with
.class - Pass all those files to
jarto package intoPackage.jar
Solution 3: Switch to the Compiled Classes Directory First
Navigate to the root folder where all your .class files are stored (skip the source folders with .java files entirely). For most Android Studio projects, this is typically:
cd app/build/intermediates/javac/debug/classes
Then package everything in this directory (which should only be .class files and package subdirectories):
jar -cf ../../../../../Package.jar *
The ../../../../../ part just navigates back up to your project root to place the jar file there—adjust the number of ../ based on your directory structure.
Bonus: Use Maven/Gradle (Since You Know It’s More Convenient)
Since you mentioned Maven is easier, for completeness, here’s a quick tip: configure the Maven Jar Plugin in your pom.xml to automatically package only compiled classes, no source files:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.3.0</version> <configuration> <includes> <include>**/*.class</include> </includes> </configuration> </plugin> </plugins> </build>
Run mvn package and it’ll handle the rest without manual commands!
内容的提问来源于stack exchange,提问作者Jared Nielsen

