Java Thin JRE jar packaged as EXE

Source: Internet
Author: User

#开始

In recent days have been busy with one thing, that is to try to streamline the JRE, I do not understand why Oracle official not out of EXE packaging tools ...

There are many articles on the network to streamline the JRE, but the original seems to be few, most of them are forwarded the same blog, here borrowed a lot of ideas and methods do not know is not the original

These two days harvest is also very big, here and everyone to share my results. and the principle ....

Thank you to the great gods on the web for the benefits of this tutorial:)

Although this blog post is long but actually because I am too wordy ... It's not hard to do and suggest looking at the general flow first

#成果

  

This is a chat room that I wrote shortly before the client, source is here: https://github.com/LonelySinging/JavaChatRoom-client.git

The entire JRE and the finished jar package are added together and packaged as EXE, only 13MB, but really, it still feels big because the jar itself is only 13KB, so that means the JRE environment is really big. The complete JRE is 197MB qaq

#开始

So let's get started now.

Suppose now we have

1. Need to pack the jar package (I'm Client.jar here)

2. One WIN10 64-bit computer JDK with Java environment is version 1.8

3. Environments that can run Java code (I'm Eclipse here)

4. Edelweiss Sword (I am a built-in version)

5. notepad++

#分析jre目录 (I just learned Java not long enough to understand the original reason is not much, so wrong don't hit me Qaq)

This is the jdk1.8 inside the JRE directory, the main is the bin and Lib directory

#bin目录

The bin directory is the location of several commands, such as Java.exe, which should also be the ontology of the JVM virtual machine.

  

Here is Java.exe is the key to start the jar and a lot of DLL files to streamline the bin directory is the key to streamline these DLL files, the idea is to meet the Java.exe run

Then the next step is to find out how java.exe depends on those DLLs.

#lib目录

My lib directory is like this

  

Everyone open can see is a bunch of unknown files and a variety of jar packages The jar package here is the class and method that we call when we write the code.

There are also font files (in the Font folder) icon resources (inside the images folder) there is a maximum Rt.jar file size is more than 60 MB, so the core of the thin Lib directory is to streamline the Rt.jar file

The idea of streamlining is still to remove the unnecessary.

#精简开始 #精简bin目录

1. Copy the ready-to-package jar package to the bin

2. Create a new batch file (new text document) add the following (meaning to run the jar file and export all output information to the Class.txt file)

    

Java-jar-verbose:classclass. txt

Save change name to Run.bat (note that this is renamed if there are no suffix names see below)

  

3. Double-click Run Run.bat and then do all of the functions for your app are all used once (this means that even an edit box you have to try to enter different things using the arrow keys to manipulate the cursor, etc.) this is very important!!!!!!!!!!! In order to output all the classes used to the Class.txt file (the Class.txt file is used to streamline the Lib directory here regardless of him)

4. Open the Edelweiss Sword (other behavior detection software can also function the same line) click Process, and then select Java.exe and then you can find all the DLL files loaded Java.exe

    

5. Create a new folder on the desktop and create a new two folder (Bin and Lib)

    

6. In the above Edelweiss sword inside to see the DLL used and their path to find them copied to the new folder in the Bin folder to find a lot less instantaneous (if the DLL file is not in the JRE directory is not copied)

    

7. Press shift in the blanks and then the right-click menu to open the Power shell to run the following result is missing jvm.cfg This is the configuration file for the JVM virtual machine and then directly copy all the files under the Lib directory of the full JRE into its own streamlined Lib directory

And then run it again./java (note that the power shell must add./To find files from the current directory)

After doing this, you should be able to run the jar file you are preparing to package here.

Create a new batch file in the Bin directory with the following contents

Java-jar Client.jar
Pause

Copy your jar file here's my client.jar.

Double-click Run.bat to run your jar file, if that's why it's a jar file.

    

    

8. If it's all right, then the bin directory is finally streamlined. TAT (typing is tired)

#精简lib文件夹

1. Here I do the comparison of water ... I do not know the Lib folder too much, so the method of streamlining may be less low

2. The idea is that the above is not yet able to run the jar file? Then we delete a file and run it once (this is the reason why the jar was run with batch processing Qaq)

3. Mainly delete jar files from large to small can also try to delete some other files than slice file font file but may cause some bugs

4. This is after I delete

  

5. It's a stupid way to do that, but the effect is good, and then we find out that the biggest is the Rt.jar file, and then the next step is to streamline Rt.jar.

6. Extension methods I found that I could find the jar file from the Class.txt file when I read the blog but,,, can't log files that are not jars. Some files may be missing from the configuration file, but it's not going to work, but someone will. Please leave a message below me to update

#精简rt. jar file

1. Remember the above class.txt file, copy it to your new JRE directory, which is the same directory as the bin and the Lib directory (this is for the convenience of not copying also line)

2. Now deal with the Class.txt file open it with notepad++ you'll find that there's a lot of things going on, tat, I'm scared of this, but it's okay. The next time you use notepad++, it'll be easy.

3. Remove all lines without square brackets

4. Ctrl + F then search for "[opened" and then delete all rows with "[Opened") (delete a whole line)

5. Ctrl + F then search for "[Loaded" click Count, then click on Replace tab Replace all (note the count when replacing, compare the number of lines should be the same,,,,)

6. Click on the "Regular expression" box to fill in the regular expression click Count in the search target, then replace---replace All

7. So we get the following things to save

  

8. jar file is essentially a zip file then we copy the Rt.jar file to the class.txt in the same directory as the bin, Lib, class.txt, Rt.jar file or folder in the streamlined JRE directory and then right-click "Extract to Rt/" ( I use 360 compression here) so that I can get a RT folder Inside is the full content of Rt.jar

9. Then create a new folder name is the Ort folder used to put the required class file

10. Then execute the following code which is copied from someone else's blog again thanks very much to the original author [11829349?t=1489849302000]:

Code can be run directly remember to modify the first line of package ch1;

 Packagech1;/****/ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.LineNumberReader;//import InputOutput;/*** @authorknowyourself1010**/ Public classcopyusefulclasses {//file Copy   Private Static BooleanCopy (String sourcefilelocation, String objectfilelocation, String fileName) {Try //must try and catch,otherwise would compile error       {           if(Sourcefilelocation.substring (Sourcefilelocation.length ()-1)! = "/") {sourcefilelocation+= "/"; }           if((Objectfilelocation.substring (Objectfilelocation.length ()-1))! = "/") {objectfilelocation+= "/"; } inputoutput InputOutput=NewInputOutput (); byte[] B =InputOutput.           Dataoutputfully (Sourcefilelocation, fileName);           Inputoutput.datainputfully (Objectfilelocation, fileName, b); return true;//if success then return True       } Catch(Exception e) {System.out.println ("Error!"); return false;//if fail then return False       }   }   //read path, copy   Private Static intDealclass (String needfile, String sdir, string odir)throwsIOException {intsn = 0;//Number of successes       if(Odir.length () > 0 && sdir.length () > 0) {           if((Sdir.substring (Sdir.length ()-1))! = "/") {Sdir+= "/"; }           if(Odir.substring (Odir.length ()-1)! = "/") {Odir+= "/"; } File Usedclass=NewFile (Needfile); if(Usedclass.canread ()) {String line=NULL; LineNumberReader Reader=NewLineNumberReader (NewInputStreamReader (NewFileInputStream (usedclass),"UTF-8"));  while(line = Reader.readline ())! =NULL) { line=Line.trim (); if(Line.contains (".") | | line.contains ("/"))) {                       //format the direction from package name to pathString dir = Line.replace (".", "/"); //Filter the file name.String tmpdir = dir.substring (0, Dir.lastindexof ("/")); String sourcefilelocation= Sdir +Tmpdir; String objectfilelocation= Odir +Tmpdir; String FileName=dir.substring (Dir.lastindexof ("/") + 1, Dir.length ())+ ". Class"; File Fdir=NewFile (objectfilelocation); if(!fdir.exists ()) fdir.mkdirs (); BooleanCOPY_OK =copy (sourcefilelocation, objectfilelocation, fileName); if(COPY_OK) SN++; Else{System.out.println (line); }                   } Else{sn=-1; }               }           }       }       returnSN; }   /**    * @paramargs*/    Public Static voidMain (string[] args) {//TODO auto-generated Method Stub       Try{BufferedReader Lineoftext=NULL; //get need classes log file directionSystem.out. println ("Absolute path of the Class.txt file to read:"); Lineoftext=NewBufferedReader (NewInputStreamReader (system.in)); String Needfile=Lineoftext.readline (); //Get source folder directionSystem.out. println (Needfile+ "\ n Enter the path of the Rt folder after Jre/lib/rt.jar decompression:"); Lineoftext=NewBufferedReader (NewInputStreamReader (system.in)); String Sdir=Lineoftext.readline (); //Get Object Folder directionSystem.out. println (Sdir+ "\ n re-enter the ORT (the folder of the useful. class file that you want to store the copy over):"); Lineoftext=NewBufferedReader (NewInputStreamReader (system.in)); String Odir=Lineoftext.readline (); System.out.println (Odir+ "\ n"); intsn =Dealclass (Needfile, Sdir, Odir);       System.out.print (SN); } Catch(IOException e) {//TODO automatically generates catch blocksE.printstacktrace (); }   }}

When you run it, fill in the content.

    

First enter the absolute path of the usedClasses.txt, enter the path of the Rt folder where the Jre/lib/rt.jar is extracted after the input, enter, and then input ORT (the folder of the useful. class file to which you want to store the copy). Then wait a few minutes, the period will be prompted, your product program used by the JRE does not contain the class does not exist, do not care, because we only copy the Rt file in the. class file (This paragraph is copied from the above code on the blog)

11. In this case, in the Ort folder there are a lot of folders like Java, javax what the full selection of these folders right-click Add to Ort.zip

12. Renamed to Rt.jar after getting Ort.zip file

13. Delete the Rt.jar file in the Lib directory with the Rt.jar file above (that is, our own packaging) to replace

14. Run the Run.bat file in the bin directory and then, if successful, test the various functions to confirm that the JRE environment has been streamlined. You can look directly at the following EXE packaging stage

15 If there's a mistake, it should be like this. The words here are obviously missing from the class file.

    

16. On the thin Rt.jar file, right-click on 360 compression to open

17. Open the previously unzipped Rt.jar folder (The Rt folder after the full Rt.jar file unpacked)

18. Depending on the path of the missing class file in the hint, locate the missing class file in the 360 compression window and the RT folder and drag it to the 360 compression window to ensure that the class file location is the same (for example, the class file path in the Rt folder is Java/lang Directory in the 360 compression should also be this directory) if you add an error then close the window

19. Re-run the Run.bat batch file in the Bin directory may also be wrong to continue the last step until there is no error

20. In this case, the JRE environment has been streamlined and successful: The next step is to package it as an EXE.

#打包成exe

1. This is relatively simple to use a ready-made tool is the virtual file Packaging tool (Enigma) 8.10 http://www.greenxf.com/soft/166563.html

2. However, this software seems to be not the role of the command line to solve the problem is to write a launcher in C Qaq (other languages as long as an EXE is OK) but it is directly in C language execution Java-jar Client.jar This command will have a problem is that there will be a console Window (I am here is the graphical interface if there is no graphical interface, then do not have to think about it) this is said to run with JAVAW. No console window But I failed./qaq don't know why, so I need to do this next.

3. Compile an EXE file C language code as follows   Explain C language if it is a console program to run the time or there is a console window of all the established project is the Win32 project is the default with the window of the kind if there are small partners do not know how to get a message I will add

" stdafx.h "  " windowless vbs runs. h"int  apientry _twinmain (_in_ hinstance hinstance,                     _in_opt_ hinstance hprevinstance,                     _in_ LPTSTR    lpcmdline,                     int        nCmdShow) {    system ("run.vbs");     return 0 ;}

The core code is System ("Run.vbs");

4. Then the next thing to write Run.vbs content is to run a batch called Run.bat and hide the window.

Set ws = CreateObject ("wscript.shell")   "cmd/c run.bat ", vbhide

5. Modify the contents of the Run.bat file under the bin directory and copy it to the same directory as the bin and Lib folders.

-jar Client.jar

6. The above two steps completed the GUI interface Java Program Hide Console window run and then put the above compiled launcher EXE in the Bin, Lib folder with the same directory as the final double-click Run.vbs or initiator. exe should be run without a console window

7. Finally, it's time to finally pack. TAT Start Packaging Tool

    

8. A. Main program Select Initiator B. Add C. Add folder recursion D. Find your streamlined JRE directory is a directory containing bin, lib, Run.bat, Run.vbs, initiator. exe. Select a folder by default click OK

9. Select Folder Options tick the Compress files checkbox and delete files when exiting delete It's not very important, but if you have more files, you may be able to speed up the next time you open it.

10. Then just click Pack and wait.

#最终成果 Qaq I'm so excited to cry

  

You see that? The entire environment, plus the jar packaged as EXE, is less than 13MB.

Finally double-click to run the TAT surprise discovery succeeded!!!!!!!!!!!!!!!!!!!!!!!!!!

#期间可能遇到的问题

1. class file is missing too much this is mainly when generating the Class.txt file without having to use all of the program functions once caused by the so-called use including the click Window and the function of each component

2. Adding a class file to the Rt.jar file is not added this may be because your program is still running need to close the console window

3. Sometimes adding a class file to Rt.jar does not solve the problem then replace the entire folder with the relevant

4. After the completion of your program may have a variety of bugs then you have to let the console window and look at the exception to see the missing class file to add him to the same folder in Rt.jar

5. You can't double-click the run prompt to lose the DLL file then you have to install the runtime Baidu Runtime collection can be

6. If you have any questions, please leave a message below, please leave a message thank you:)

Thanks for the following articles:

11829349?t=1489849302000

6973887

52792361

There are a few of them. Thank you ^_^

-------Forwarding Please specify the source thank you

  

Java Thin JRE jar packaged as EXE

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.