How to convert AAR to JAR - java

Situation:
I intend to use a Java library and I only have an AAR file from a Maven repository but I need the JAR file.
Background story:
I tried to compile a library, but its Gradle structure was unstable. So I asked for a compiled jar file, and its developer handed me an aar file from some Maven repository (the developer couldn't compile his own project).
The Gradle configuration was a mess, it depended on multiple libraries and Gradle has thrown some exceptions.
I tried to use it in my IDEA IDE, but it couldn't see it. A library project should be able to be compiled into a jar file, right?
Question:
What should I do to convert that AAR file to a JAR file?

The AAR file consists of a JAR file and some resource files (it is basically a standard zip file with a custom file extension). Here are the steps to convert:
Extract the AAR file using standard zip extract (rename it to *.zip to make it easier)
Find the classes.jar file in the extracted files
Rename it as you like and use that jar file in your project

.aar is a standard zip archive, the same one used in .jar. Just change the extension and, assuming it's not corrupt or anything, it should be fine.
If you needed to, you could extract it to your filesystem and then repackage it as a jar.
1) Rename it to .jar
2) Extract: jar xf filename.jar
3) Repackage: jar cf output.jar input-file(s)

As many other people have pointed out, just extracting the .jar from the .aar file doesn't quite cut it as resources may be missing.
Here are the steps that worked for me (context of Android, your mileage may vary if you have other purposes):
Rename the .aar file to .zip and extract.
The extracted folder is an ADT project that you can import in Eclipse with some minor modifications (see below)!
In the extracted folder rename the contained file classes.jar to whatever you like (in this example myProjectLib.jar) and move it to the lib folder within the extracted folder.
Now in order for Eclipse to accept it you need to put two files into the extracted folder root:
.project
.classpath
To do that, create a new Android dummy project in Eclipse and copy over the files, or copy over from an existing Android project.
Open the .project file and look for the XML name tag and replace the contents of it with myProjectLib (or whatever you called your jar file above) and save.
Now in Eclipse you can File -> New -> Project -> Android Project from existing source.. and point to the extracted folder content.
After import right click on the newly created project, select Properties -> Android, and check Is Library.
In your main project that you want to use the library for, also go to Properties -> Android and add the newly added myProjectLib to the list of dependencies.

For those, who want to do it automatically, I have wrote a little two-lines bash script which does next two things:
Looks for all *.aar files and extracts classes.jar from them
Renames extracted classes.jar to be like the aar but with a new extension
find . -name '*.aar' -exec sh -c 'unzip -d `dirname {}` {} classes.jar' \;
find . -name '*.aar' -exec sh -c 'mv `dirname {}`/classes.jar `echo {} | sed s/aar/jar/g`' \;
That's it!

Android Studio (version: 1.3.2) allows you to seamlessly access the .jar inside a .aar.
Bonus: it automatically decompiles the classes!
Simply follow these steps:
File > New > New Module > Import .JAR/.AAR Package to import you .aar as a module
Add the newly created module as a dependency to your main project (not sure if needed)
Right click on "classes.jar" as shown in the capture below, and click "Show in explorer". Here is your .jar.

Resource based .aar-projects
Finding the classes.jar file inside the .aar file is pretty trivial. However, that approach does not work, if the .aar-project defined some resources (example: R.layout.xyz)
Therefore deaar from CommonsGuy helped me to get a valid
ADT-friendly project out of an .aar-file. In my case I converted
subsampling-scale-image-view. It took me about an hour to set up ruby on my PC.
Another approach is using android-maven-plugin for Eclipse/ADT as
CommonsGuy writes in his blog.
Yet another approach could be, just cloning the whole desired project
as source from git and import it as "Existing Android project"

The 'aar' bundle is the binary distribution of an Android Library Project. .aar file
consists a JAR file and some resource files. You can convert it
as .jar file using this steps
1) Copy the .aar file in a separate folder and Rename the .aar file to .zip file using
any winrar or zip Extractor software.
2) Now you will get a .zip file. Right click on the .zip file and select "Extract files".
Will get a folder which contains "classes.jar, resource, manifest, R.java,
proguard(optional), libs(optional), assets(optional)".
3) Rename the classes.jar file as yourjarfilename.jar and use this in your project.
Note: If you want to get only .jar file from your .aar file use the
above way.
Suppose If you want to include the manifest.xml and resources with your .jar file means
you can just right click on your .aar file and save it as .jar file directly instead of
saving it as a .zip. To view the .jar file which you have extracted, download JD-GUI(Java Decompiler). Then drag and drop your .jar file into this JD_GUI, you can see the .class file in readable formats like a .java file.

If you are using Gradle for your builds - there is a Gradle plugin which allows you to add aar dependency to your java|kotlin|scala|... modules.
https://github.com/stepango/aar2jar
plugins {
id 'java'
id 'com.stepango.aar2jar' version “0.6” // <- this one
}
dependencies {
compileOnlyAar "com.android.support:support-annotations:28.0.0" // <- Use any AAR dependencies
}

Related

Can't Access resource path, only the target path

I want to access the resource's form of my project "\src\main\resources" but for any reason I can only access the target classes.
Here is my code:
System.out.println(Main.class.getResourceAsStream("/123.txt")); // java.io.BufferedInputStream#66cd51c3
System.out.println(Main.class.getResource("/123.txt")); // file:/C:/Users/Raul/workspace/Serial/target/classes/123.txt
System.out.println(Thread.currentThread().getContextClassLoader().getResource("123.txt").getPath()); // /C:/Users/Raul/workspace/Serial/target/classes/123.txt
and here my Project Dirs:
The thing is, even if I delete all the files in the target/classes and run the code, the compiler will copy the files from "src/main/ressources" into "target/classes" and read them from there.
I want to access the resource's form of my project "\src\main\resources" but for any reason i can only access the target classes.
I think the question is answered by user #VGR. Just to clarify it in another words:
You put your resources in the /src/main/resources folder, and these resouces will be copied as is into the /target/classes folder when you build your project.
Example
src/main/resouces/123.txt -> target/classes/123.txt
src/main/resources/myresources/145.txt -> target/classes/myresources/145.txt
...
Now if you run the program inside of your IDE you'll observe the following:
System.out.println(Main.class.getResource("/123.txt"));
output: file:/C:/Users/Raul/workspace/Serial/target/classes/123.txt
System.out.println(Main.class.getResource("/myresources/145.txt"));
output: file:/C:/Users/Raul/workspace/Serial/target/classes/myresources/145.txt
But if you open the generated jar file you'll not see the target folder because the file 123.txt will be on the root of the jar file and the file 145.txt will be under the folder myresources/145.txt.
The folder target is just an output directory for the build tool and will not be packaged within your jar file.
Now to the following question:
the problem is that i dont know how to export the target classes to my jar, or how can I get "src/main/ressources" as return value.
To answer this question you have to look into your pom.xml file on the root of your project. There should be a <packaging>jar</packaging> entry in it. If that is so you create the jar file as follows:
Option 1: from the command line
mvn clean install
the jar file will be created and copied into the folder target.
Option 2: from within Eclipse (for example)
right click on the pom.xml > Run AS > Maven install
the jar file should also be generated and copied into the folder target.
Note: on your screenshot there are two jar files: core-0.0.1-SNAPSHOT.jar and Serial-0.0.1-SNAPSHOT.jar; remove them (mvn clean or right click > Run AS > Maven clean) before generating the jar file. The reason is Maven can only generate one jar file per Maven module / project, afaik.
You are seeing the intended behavior. A Java program is compiled into an executable form—meaning, .class files and resources. When other users run your program, they will not have access to the source, so your code should not assume your source tree will be available.
Simply put, your code is correct as is. Do not attempt to read the source tree. If you want target/classes to contain up-to-date files, rebuild your project.
A word of caution: Never use the getPath() method of URL to convert a URL to a file name. There are many characters which are not permitted in URLs, and those characters will be “percent-escaped” in order to conform to the URL specification; as a result, the path portion of a URL is not a valid filename! The only correct way to convert a URL to a file is Paths.get(url.toURI()). However, you should not even try to convert a resource to a file at all, because once you move on to packaging your programs in .jar files, your resources will not exist as regular files at all, only as entries in .jar files (which are actually just zip files with some Java-specific entries added).

How to turn folder into jar - Code

Hi im busy on a application that decompiles a jar the pastes files into the folder of the decompiled jar, it then compresses the folder into a jar.
Decompiling and copying works, but i can't manage to get the folders contents to be jared (compressed into jar), i did about 3hrs research and found only outdated methods. please help.
-Regards
marko5049
EDIT MORE INFO:
I apologize i mean i cant get my application to turn a folder into a jar file, my application is an modification installer for a jar file. and it extracts the jars files, then adds the modification and then, is supposed to then turn the folder back into a jar file so that the modification is installed. The jar file is not executable.
This worked for me for a MAC OSX:
Open Terminal at the folder with the jar file and run the following commands
unzip mylib.jar -d jarfolder
//You can then change whatever you need and finally run the command below
jar cvf mylib.jar -C jarfolder/ .
Given that you want to create the JAR through code; you can use JarOutputStream for that. There is an example at this link that contains code to create a JAR file given a File[] containing all the input files.
As for creating the list of files given a starting input path, see Recursively list files in Java.
You could either build a list of files then just use code like in the above example, or you could recursively scan files and add them to the JAR as you go.
If you are using Java 7 and you know your users are too you can also use Files.walkFileTree() with a FileVisitor that adds entries to the JAR as it visits files.
Original answer before OP clarified:
Is there something wrong with:
jar cf my-application.jar folder1 folder2 folder3 etc
The JDK comes with a jar utility to create JAR files.
You can read an official tutorial on it here: Creating JAR Files. It is very straightforward.
If you want to create a runnable JAR, you can create a manifest file that has the main class and other options in it. The linked tutorial describes that process.
The short answer is, ZIP the folder, then rename it to a JAR file.
for windows just make the folder as winrar file.,
to do this right click the folder and click "7 -zip" then
choose "add to foldername.zip".
now a rar file is created with the same folder name.
Then open the cmd in current folder directory
type "mv foldername.zip foldername.jar"
Now you got the executable jar file with your corresponding folder.
The easiest way to make it .. put your folder to C:\Program Files\Java\jdk1.8.0_221\bin and then reach till the same path from CMD then run this
jar cvf Name_your_jar.jar folder
Following command worked for me in Windows 10 and jdk-8u212
jar cf my-application.jar folder1 folder2 folder3 etc
You can put your files in a zip folder. Then convert the zip file into Jar format.A .jar extension file is a Java Archive format file. It is used to store a large amount of files into one single file. You can try a free online file converter without downloading a new software on your computer. There are various online file converters available on Google. I would recommend Convert zip to jar
I hope it helps.
I just found this question and its answers are more useful for your problem:
how to zip a folder itself using java
2 tips :
1、a jar is exactly a zip. So, you just need to zip your folder, and rename it to jar
2、be careful that you should zip your whole folder without changing the relative path of the files, but not just extract all the .class files and zip them together. Because when you run the jar, the class package should be consistent with its path.
I suggest trying to create a regular .ZIP file in Windows.
You need to get 7-zip in order to view the .JAR file you are creating. You should just paste contents into the .ZIP, then rename the file type from .ZIP to .JAR, this worked for me and I hope this works for you.
.JARs are basically .ZIPs created by the Oracle Java client, so you need special file viewing software such as 7-zip or WinRAR to view it for some reason.
You can also revert .JARs to .ZIPs by renaming the file type. You might have to mod your computer with RegeEdit or something to have access to renaming your file types.
I hope this helps.

Netbeans Clean & build classes

When I clean and build a project in NetBeans, the .jar file appears in the dist folder, like it's supposed to. But what if I have multiple files under the project? What happens to those files? E.g. I have a Game project, and under it are the different characters(knight, rogue, etc.) but I only see a game.jar file when I clean and build, I want to know what happens to the individual files. Thanks
Those files should be in the jar file as compiled .class files. It's easy to double check what's in the jar file since it's in zip format. You can use a program like 7-Zip to open it, or rename it to the zip extension (e.g. from mygame.jar to mygame.zip) and whatever OS you're using probably has some way to open it.
When you open or extract the jar file you'll find the compiled class files in a directory structure that reflects your package structure. For example, if you have Knight.java in the directory src/game/characters/Knight.java in the jar file you'll find something like classes/game/characters/Knight.class.
The name "jar" is an abbreviation of "Java archive". It stores all the classes and other resources (for example, images) in a project.
The classes you have defined in .java files will be compiled into .class files - these are contained in the .jar file.
All resources get compiled into the JAR file. If you want a separate JAR for the resources, you'll need to split the project into two maven projects: one jar for the code, one for the resources. You can then create a third project that would generate a distribution.
That's a lot of work, though. It's.a lot easier tO keep everything in one JAR unless you have explicit dynamic loading requirements.

How to resolve classes with source src-jar library in Eclipse?

I have added this jar file to my project's build path under "libraries":
http://sunet.dl.sourceforge.net/project/jeplite/jeplite/jeplite-0.8.7/jeplite-0.8.7a-src.jar
and cannot get Eclipse to resolve ANY of the included classes.
Packages are visible, but no classes.
Error message is:
"JEP cannot be resolved to a type"
In eclipse, it should be on the build path if its a source tree .... Remember , a jar is just a glorified zip file, so be sure that the binaries are actually in your jar file. The steps to test are
1) unzip the jar file
2) if its source : then either try adding it to your build path, or just directly import the source folders into your project
3) if you see class files in the jar, then it should be okay to add them to "libraries"
This is only a jar containing the source code. You need a jar with the compiled classes in it. Try the jeplite-0.8.7a-bin.jar.

Updating .class file in jar

I want to update a .class file in a jar with a new one. What is the easiest way to do it, especially in the Eclipse IDE?
This tutorial details how to update a jar file
jar -uf jar-file <optional_folder_structure>/input-file(s)
where 'u' means update.
Do you want to do it automatically or manually? If manually, a JAR file is really just a ZIP file, so you should be able to open it with any ZIP reader. (You may need to change the extension first.) If you want to update the JAR file automatically via Eclipse, you may want to look into Ant support in Eclipse and look at the zip task.
Use jar -xvf to extract the files to a directory.
Make your changes and replace the classes.
Use jar -cvf to create a new jar file.
Simply drag and drop your new class file to the JAR using 7-Zip or Winzip. You can even modify a JAR file that is included in a WAR file using the parent folder icon, and click Ok when 7zip detects that the inside file has been modified
Jar is an archive, you can replace a file in it by yourself in your favourite file manager (Total Commander for example).
A JAR file is just a .zip in disguise. The zipped folder contains .class files.
If you're on macOS:
Rename the file to possess the '.zip' extension. e.g. myJar.jar -> myJar.zip.
Decompress the '.zip' (double click on it). A new folder called 'myJar' will appear
Find and replace the .class file with your new .class file.
Select all the contents of the folder 'myJar' and choose 'Compress x items'. DO NOT ZIP THE FOLDER ITSELF, ONLY ITS CONTENTS
Miscellaneous - Compiling a single .class file, with reference to a original jar, on macOS
Make a file myClass.java, containing your code.
Open terminal from Spotlight.
javac -classpath originalJar.jar myClass.java This will create your compiled class called myClass.class.
From here, follow the steps above. You can also use Eclipse to compile it, simply reference the original jar by right clicking on the project, 'Build Path' -> 'Add External Archives'. From here you should be able to compile it as a jar, and use the zip technique above to retrieve the class from the jar.
Editing properties/my_app.properties file inside jar:
"zip -u /var/opt/my-jar-with-dependencies.jar properties/my_app.properties". Basically "zip -u <source> <dest>", where dest is relative to the jar extract folder.
High-level steps:
Setup the environment
Use JD-GUI to peek into the JAR file
Unpack the JAR file
Modify the .class file with a Java Bytecode Editor
Update the modified classes into existing JAR file
Verify it with JD-GUI
Refer below link for detailed steps and methods to do it,
https://www.talksinfo.com/how-to-edit-class-file-from-a-jar/
1) you can extract the file into a folder called
jarname.jar
and then replace the file in the folder, handy if you are updating the class a lot while debugging
2) you can extract the jar replace the file then the jar it up again
3) Open the jar with 7 zip and drag and drop your new class in to copy over the old one
You can find source code of any .jar file online, import the same project in your IDE with basic setups. Make necessary changes in .java file and compile it for .class files.
Once compilation is done You need to extract the jar file, replace the old .class file with new one.
And use below command for reconstruct .jar file
Jar cf test.jar *
Note : I have done so many time this changes in our project, hope you will find it useful.
An alternative is not to replace the .class file in the jar file. Instead put it into a new jar file and ensure that it appears earlier on your classpath than the original jar file.
Not sure I would recommend this for production software but for development it is quick and easy.

Categories