Compiling source code makes .jar significantly smaller? - java

///WARNING- I DO NOT KNOW ANY LANGUAGES/HAVE NO USED ECLIPSE BEFORE\\
I'm currently trying to get a .jar file compiled in Java8 to compile in Java7, but seem to be having trouble, I have the source code intact so that is not the problem. It compiles fine, but the finished .jar is smaller than the original by a large margin. I believe the problem lies in my inexperience with Eclipse meaning I problably did something wrong.
Source Folder Structure
src\com\darkblade12\enchantplus...java files
Contents Of Each Folder

If you have some doubts about eclipse being behind the problem, try to compile it directly using the Command line Interface with the target version version of java by using javac.
Example for Windows:
set JAVA_HOME=C:\Program Files (x86)\Java\jre1.7.0_21
javac com/darkblade12/enchantplus/*.java
jar cvf program.jar -C com/darkblade12/enchantplus
Then compare your jar generated by eclipse and this generated directly from the command line.
Another way to verify is to open the jar file with and archive manager like 7-zip and verify its content.

Related

How to decompile to java files intellij idea

IDEA has a great built-in feature - decompiler. It works great.I can copy source code, but I cannot find option to extract all decompiled java classes to java files.
This project has a lot of java classes and packages, so I will be to long to copy this manually.
Does anyone know how to extract to java source files.
Thx
As of August 2017 and IntelliJ V2017.2, the accepted answer does not seem to be entirely accurate anymore: there is no fernflower.jar to use.
The jar file is called java-decompiler.jar and does not include a main manifest... Instead you can use the following command (from a Mac install):
java -cp "/Applications/IntelliJ IDEA.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar" org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler
(you will get the wrong Usage command, but it does work).
Follow instructions for IntelliJ JD plugin. Or see an excerpt from the instructions below.
java -jar fernflower.jar [<source>]+ <destination>
+ means 1 or more times
<source>: file or directory with files to be decompiled. Directories are recursively scanned. Allowed file extensions are class, zip and jar.
<destination>: destination directory
Example:
java -jar fernflower.jar -hdc=0 -dgs=1 -rsy=1 -lit=1 c:\Temp\binary\ -e=c:\Java\rt.jar c:\Temp\source\
Be aware that if you pass it a ".jar" file for the source, it will create another ".jar" file in the destination, however, within the new ".jar" file, the files will be .java instead of .class files (it doesn't explode the jar).
UPDATE
People ask me: How do I get the fernflower.jar?
If you have any IntelliJ product installed, chances are that you already have the Fernflower decompiler on your computer. IntelliJ IDEA comes with Java Bytecode Decompiler plugin (bundled) which is a modern extension of Fernflower.
Locate the file in ${IntelliJ_INSTALL_DIR}\plugins\java-decompiler\lib\java-decompiler.jar (example: C:\Program Files\JetBrains\IntelliJ IDEA 2018\plugins\java-decompiler\lib).
Copy it somewhere and rename to fernflower.jar (optional).
This JAR is not executable, so we can't run it using java -jar. However something like this works:
java -cp fernflower.jar org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler [<source>]+ <destination>
org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler is the class that contains the main method to run the decompiler.
Example:
mkdir output_src
java -cp fernflower.jar org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler -hdc=0 -dgs=1 -rsy=1 -lit=1 ./input.jar ./output_src
If you don't have IntelliJ products installed, either download it now (available on jetbrains.com) or make your own decompiler executable from sources (available on Github).
Open an existing project or create a new one.
Go to Project structure settings > Libraries. Add the jar you want to decompile in libraries by clicking the + symbol.
Go to the Project tool window shown on the left. Search for jar name that you added in the previous step. Navigate to the desired class or package.
You can see the decompiled java files for that jar.
You could use one of these (you can both use them online or download them, there is some info about each of them) :
http://www.javadecompilers.com/
The one IntelliJ IDEA uses is fernflower, but it can't handle recent things - like String/Enum switches, generics (didn't test this one personally, only read about it), ...
I just tried cfr from the above website and the result was the same as with the built-in decompiler (except for the Enum switch I had in my class).
Try
https://github.com/fesh0r/fernflower
Download jar from
http://files.minecraftforge.net/maven/net/minecraftforge/fernflower/
Command :
java -jar fernflower.jar -hes=0 -hdc=0 C:\binary C:\source
Place your jar file in folder C:\binary and source will be extracted and packed in a jar inside C:\source.
Enjoy!
The decompiler of IntelliJ IDEA was not built with this kind of usage in mind. It is only meant to help programmers peek at the bytecode of the java classes that they are developing. For decompiling lots of class files of which you do not have source code, you will need some other java decompiler, which is specialized for this job, and most likely runs standalone, like jad, fernflower, etc.
Some time ago I used JAD (JAva Decompiler) to achieve this - I do not think IntelliJ's decompiler was incorporated with exporting in mind. It is more of a tool to help look through classes where sources are not available.
JAD is still available for download, but I do not think anyone maintains it anymore: http://varaneckas.com/jad/
There were numerous plugins for it, namely Jadclipse (you guessed it, a way to use JAD in Eclipse - see decompiled classes where code is not available :)).
I use JD-GUI for extract all decompiled java classes to java files.
Someone had gave good answers. I made another instruction clue step by step.
First, open your studio and search. You can find the decompier is Fernflower.
Second, we can find it in the plugins directory.
/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar
Third, run it, you will get the usage
java -cp "/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar" org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler
Usage: java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination>
Example: java -jar fernflower.jar -dgs=true c:\my\source\ c:\my.jar d:\decompiled\
Finally, The studio's nest options for decompiler list as follows according IdeaDecompiler.kt
-hdc=0 -dgs=1 -rsy=1 -rbr=1 -lit=1 -nls=1 -mpm=60 -lac=1
IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR to "0",
IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES to "1",
IFernflowerPreferences.REMOVE_SYNTHETIC to "1",
IFernflowerPreferences.REMOVE_BRIDGE to "1",
IFernflowerPreferences.LITERALS_AS_IS to "1",
IFernflowerPreferences.NEW_LINE_SEPARATOR to "1",
**IFernflowerPreferences.BANNER to BANNER,**
IFernflowerPreferences.MAX_PROCESSING_METHOD to 60,
**IFernflowerPreferences.INDENT_STRING to indent,**
**IFernflowerPreferences.IGNORE_INVALID_BYTECODE to "1",**
IFernflowerPreferences.VERIFY_ANONYMOUS_CLASSES to "1",
**IFernflowerPreferences.UNIT_TEST_MODE to if (ApplicationManager.getApplication().isUnitTestMode) "1" else "0")**
I cant find the sutialbe option for the asterisk items.
Hope these steps will make the question clear.
2022 UPDATE
Like any experienced developer who's being honest, I have to admit it -- I'm lazy. More is less and less is better when it comes to typing. The answers from #naXa and #yan are fine, except for having to open a terminal and type :-(
To decompile a jar right from within intellij, create a reusable JAR Application run configuration:
Copy java-decompiler.jar to a folder in your project (I used lib). Get from:: Windows: C:\Program Files\Intellij\plugins\java-decompiler\lib; or from github (documentation is here)
Copy source jar or class files to same folder
Create a run configuration with settings like these:
Path to JAR: browse to java-decompiler.jar
Program arguments: -hdc=0 -dgs=1 -rsy=1 -lit=1 your.jar lib
Working directory: lib
JRE: 11
In this case, your.jar is the source and lib is the output directory. Save it, run it, and watch it do its thing :-)
Need to do it again with different class files or jars? Duplicate the run config and update Program arguments.
---- package jar (java) jar -cvfM0 test.jar
---Decompile jar(class)>>>>>>>>>jar(java) java -cp "C:\Program Files\JetBrains\IntelliJ IDEA 2020.1\plugins\java-decompiler\lib\java-decompiler.jar" org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler -dgs=true C:\ Users\luo\Desktop\sf1\pxks\test.jar C:\Users\luo\Desktop\sf1
Unzip manually
Or use the following command to decompress
find the path
cd..
decompress
jar -xvf test.jar
Reference http://t.csdn.cn/3YLK4

Running a java project in terminal with multiple .java files (multiple attempts described inside)

I have been doing a coding exercise inside the IntelliJ IDEA Community Edition 14 IDE, using OpenJDK.
The project is split over 4 .java files all in the same package.
My end goal is to run this in the terminal/bash (I use System.console().readLine() which doesnt play nicely in the IDE's console).
I've tried navigating to the directory where these 4 files reside (they all reside in the same dir) and tried:
javac -classpath . BibliotecaApp.java Book.java BookManager.java LibraryDB.java
This creates 4 corresponding .class files fine.
The Main is in bibliotecaApp.java/class, so I try run it by:
java BibliotecaApp
But I get the error
Exception in thread "main" java.lang.NoClassDefFoundError: BibliotecaApp (wrong name: com/twu/biblioteca/BibliotecaApp)
Plus about 13 lines of specifics.
Now googling this error seems to be a class path problem, and this is where I get stuck.
From places I've read, usingecho $PATH gives me:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
This is still from the directory of the .java files above.
That path means nothing to me. I have no idea what it is or what it does, or what even a classpath is! Theres alot of resources out there on setting a classpath, but they aren’t helping me because I don't know what it's meant for.
That was a dead end for me. I tried to create a .jar instead using IDEA's Build Artifacts as seen HERE. It created a .jar file but when I navigate to that directory and try run it via:
java -jar biblioteca_jar
I get
Error: Invalid or corrupt jarfile biblioteca_jar
Another issue is that in the file explorer, the file actually comes out as biblioteca.jar, but ls on that dir shows biblioteca_jar. Is that normal?
The code is on my GitHub if that helps anything
https://github.com/botagar/twu-biblioteca-JohnGeddes
Based on your compiler step, change this
java BibliotecaApp
to
java -cp . BibliotecaApp
Which will add the current directory to the classpath for the java runtime environment. See also the Oracle Technote Setting the Class Path.
A jar file is a kind of zip, and should have a .jar extension. So this
java -jar biblioteca_jar
should probably be
java -jar biblioteca.jar
And you can check if the file is valid with any zip archive reader. Including jar itself,
jar tvvf biblioteca.jar
Edit
Based on your comments below,
cd ~/Documents/ThoughtWorks Uni/TWU_Biblioteca-master/src/
and then
java -cp . com.twu.biblioteca.BibliotecaApp

Create a jar file using compiled class files and an existing MANIFEST.MF file

Is it possible to take existing .class files and a MANIFEST.MF to create a jar file?
Is there a library that can create a "valid" jar-file? I tried it manually and it didn't work (using 7zip).
ERROR: "Invalid or corrupt jar file"
If everything has been compiled before, it should (in my understanding) theoretically work, if you create a new zip file, put all the files in it in the original structure and then rename it to "jar".
My idea is to program something like this with java code. A solution where I could add a file to an existing jar, would also be ok.
If you're interested in why I want to use this, look at my initial question: Compile javacode out of a running java accpilaction - on a system that hasn't JDK installed
Well Jar -cf
Try the jar command in $JAVA_HOME/bin
$JAVA_HOME is the path to you JRE/JDK installation

Compiles with NetBeans but can't compile or run from bash

I have been researching this for weeks and can't seem to get it figured out.
I have a Java program that I have written using NetBeans. It has several imports or .jar files it relies on. It runs fine in NetBeans. But I can't figure out how to call the .jar files and compile from the bash command line. I am using a Mac. I have read several posts on this and none so far have made sense to me. There are 26 imports being used in the program. I don't know if I need to use Ant or specify -CP or Classpath to compile. Surely I don't have to type each one of the .jar files out to compile this from the bash command line?
Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
You should be able to simply use ant with the build.xml in the Netbeans project directory. It should "just work" for you. The project will likely not build WITHOUT Netbeans installed (if you tried moving the project to a different machine, for example), but with Netbeans, it should work out of the box.
If you don't have Ant installed, you'll need to install it.
Addenda:
To build it, if you have Ant installed, you should be able to simply go the project directory, where the build.xml file is, and type "ant", and it should build and put stuff in the dist directory.
If you go in to the dist directory and type java -jar yourapp.jar, it should run, because the manifest in the jar will point to the nearby lib jar files. If you want to distribute the app, there are different options for java, such as making a Mac compatible application, or a Windows EXE, you'll need to search for those. Or you can simply distribute the contents of the dist directory and write a script to do that whole java -jar yourapp.jar command.
If you are using Java 1.6 or above, you can toss all 26 jar files into a folder and simply add
-cp folder_name/*
as your classpath argument.
Some other options are 1.) type all 26 jar files on the command line (using the -cp argument as you have mentioned) 2.) use Ant or Maven or some other build tool and list those 26 jar files in the config file for said build tool or 3.) write a quick-and-dirty shell script that will set the CLASSPATH environment variable for you and then run your javac command.

The dreaded java.lang.NoClassDefFoundError

I've looked through many of the existing threads about this error, but still no luck. I'm not even trying to package a jar or use any third-party packaging tools. I'm simply running from within Eclipse (works great) and then trying to run the exact same app from the command line, in the same location it's built to (getting this error). My goal is to be able to zip up the bin folder and send it off to be run by someone else via a command line script. Some details:
It's a command-line app and I'm using the commons-lang-2.4.jar for string utilities. That is the file that cannot be located (specificaly "java.lang.NoClassDefFoundError: org/apache/commons/lang/StringEscapeUtils")
I have that jar in my lib folder and have added it to my build path in Eclipse via right-click "Build Path -> Add to Build Path"
The .classpath file looks correct and contains the reference to the jar, but I assume that file is only used by Eclipse (contains this line: <classpathentry kind="lib" path="lib/commons-lang-2.4.jar"/>)
Could this be related to the Eclipse working directory setting? I have some internal template files that I created that are under src/templates, and the only way I can seem to get those to be seen is by setting the project working directory to AppName/src. Maybe I should be putting those somewhere else?
Let me know if any additional info would help. Surely this is something simple, but I've wasted too much time on it at this point. This is reminding me why I originally left Java back in '05 or so...
A NoClassDefFoundError basically means that the class was there in the classpath during compiletime, but it is missing in the classpath during runtime.
In your case, when executing using java.exe from commandline, you need to specify the classpath in the -cp or -classpath argument. Or if it is a JAR file, then you need to specify it in the class-path entry of its MANIFEST.MF file.
The value of the argument/entry can be either absolute or relative file system paths to a folder containing all .class files or to an individual .jar file. You can separate paths using a semicolon ;. When a path contains spaces, you need to wrap the particular path with doublequotes ". Example:
java -cp .;c:/path/to/file.jar;"c:/spacy path/to/classes" mypackage.MyClass
To save the effort of typing and editing the argument in commandline everytime, use a .bat file.
Edit: I should have realized that you're using an Unix based operating system. The above examples are Windows-targeted. In the case of Unix like platforms you can follow the same rules, but you need to separate the paths using a colon : and instead of an eventual batch file, use a .sh file.
java -cp .:/path/to/file.jar:"/spacy path/to/classes" mypackage.MyClass
Are you specifying the classpath to java on the command line?
$ java -cp lib/commons-lang-2.4.jar your.main.Class
The classpath setting you are setting in Eclispe are only for the IDE and do not affect how you application is run outside the IDE. Even if you use the Eclipse Functionality to export your application as an executable jar file there is no out of the box way to package all the jars your application depends on.
If you have packaged you application into a jar file called myapp.jar then running a command like below will run the application with the jar you depend on, if you have more than one just add them separted by ; on Windows or : on Unix:
java -jar myapp.jar -cp .;c:/pathtolibs/commons-lang-2.4.jar
If you are just running the classes directly then either run the folder containing your .class files will also need to be on the path (though I assume it already is since you are able to run the program and get errors).
Consider File -> Export -> Runnable jar to create a jar file which can be invoked directly with
java -jar yourProgram.jar
There are several variants depending on your needs.
Eclipse does not move any of the jars in your classpath into the bin folder of your project. You need to copy the util jar into the bin folder. If you move it to the root of the bin folder, you might be able to get away without any classpath entries but it's not the recommended solution. See #BalusC's answer for good coverage of that.
Eclipse doesn't build executable java classes by default. Don't ask me why, but it probably has something to do with using their own tools.jar (somewhere in plugins/org.eclipse.core ?) so that Eclipse can run without a JDK.
You can usually go to your project bin directory and do:
java -cp . MyClass
But if you have external jars, Eclipse handles those internally in another weird way, so you'll need to add those too.
make sure your jar commons-lang-2.4.jar in classpath and not redudance.
I ever add jar file to my classpath, and have 2 file jar in my classpath. After I delete it, work smooth

Categories

Resources