How to edit jar files
How to edit jar files
Modifying a file inside a jar
I would like to modify a file inside my jar. Is it possible to do this without extracting and re jarring, from within my application?
File i want to modify are configuration files, mostly xml based.
14 Answers 14
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You can use the u option for jar
From the Java Tutorials:
«Any files already in the archive having the same pathname as a file being added will be overwritten.»
Much better than making the whole jar all over again. Invoking this from within your program sounds possible too. Try Running Command Line in Java
You can use Vim:
Vim is able to edit compressed text files, given you have unzip in your environment.
As many have said, you can’t change a file in a JAR without recanning the JAR. It’s even worse with Launch4J, you have to rebuild the EXE once you change the JAR. So don’t go this route.
It’s generally bad idea to put configuration files in the JAR. Here is my suggestion. Search for your configuration file in some pre-determined locations (like home directory, \Program Files\ etc). If you find a configuration file, use it. Otherwise, use the one in the JAR as fallback. If you do this, you just need to write the configuration file in the pre-determined location and the program will pick it up.
Another benefit of this approach is that the modified configuration file doesn’t get overwritten if you upgrade your software.
Not sure if this help, but you can edit without extracting:
I have similar issue where I need to modify/update a xml file inside a jar file.
The jar file is created by a Spring-boot application and the location of the file is BOOT-INF/classes/properties
I was referring this document and trying to replace/update the file with this command:
jar uf myapp.jar BOOT-INF/classes/properties/test.xml
But with this, it wont change the file at the given location. I tried all the options also but wont work.
Note: The command I am executing from the location where jar file is present.
The solution I found is:
The xml file has been changed in the jar file.
Basically you need to create a folder structure like where the file is located into the jar file. Copy the file at that location and then execute the command.
The problem with the documentation is that, it does not have enough examples as well as explanation around common scenarios.
I want this to work for my phone.
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Here’s what I did:
That’s it. I have tested it with my Nokia and it’s working for me.
A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.
Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won’t find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.
You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.
This is a tool to open Java class file binaries, view their internal structure, modify portions of it if required and save the class file back. It also generates readable reports similar to the javap utility. Easy to use Java Swing GUI. The user interface tries to display as much detail as possible and tries to present a structure as close as the actual Java class file structure. At the same time ease of use and class file consistency while doing modifications is also stressed. For example, when a method is deleted, the associated constant pool entry will also be deleted if it is no longer referenced. In built verifier checks changes before saving the file. This tool has been used by people learning Java class file internals. This tool has also been used to do quick modifications in class files when the source code is not available.» this is a quote from the website.
Modifying a jar file
I have a jar file which is used in html file as applet. I want to modify the content of the jar file and to rebuild the jar file so that the html will work fine with the new jar file. How can i do this??
I already tried unzipping using 7zip nad modified the source and created the new jar. But when i use it in html it shows some java.lang.Classnotfound error
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You can unjar or rejar the classes and source files as you wish.
I’ve faced cases where the launcher of the app uses some sort of verification and checks for this kind of changes. I had to use a new launch script. This doesn’t seem to be your case though.
This is surely possible from the command line. Use the u option for jar
From the Java Tutorials:
«Any files already in the archive having the same pathname as a file being added will be overwritten.»
A brief test shows this quickly updates changes apart from trying to delete the file.
I haven’t seen this answer on other threads about modifying jar files, and many, marked as duplicates, suggest there is no alternative but to remake the jar completely. Please correct if wrong.
Using JAR Files: The Basics
JAR files are packaged with the ZIP file format, so you can use them for tasks such as lossless data compression, archiving, decompression, and archive unpacking. These tasks are among the most common uses of JAR files, and you can realize many JAR file benefits using only these basic features.
Even if you want to take advantage of advanced functionality provided by the JAR file format such as electronic signing, you’ll first need to become familiar with the fundamental operations.
To perform basic tasks with JAR files, you use the Java Archive Tool provided as part of the Java Development Kit (JDK). Because the Java Archive tool is invoked by using the jar command, this tutorial refers to it as ‘the Jar tool’.
As a synopsis and preview of some of the topics to be covered in this section, the following table summarizes common JAR file operations:
This section shows you how to perform the most common JAR-file operations, with examples for each of the basic features:
Creating a JAR File
This section shows you how to use the Jar tool to package files and directories into a JAR file.
Viewing the Contents of a JAR File
You can display a JAR file’s table of contents to see what it contains without actually unpacking the JAR file.
Extracting the Contents of a JAR File
You can use the Jar tool to unpack a JAR file. When extracting files, the Jar tool makes copies of the desired files and writes them to the current directory, reproducing the directory structure that the files have in the archive.
Updating a JAR File
This section shows you how to update the contents of an existing JAR file by modifying its manifest or by adding files.
Running JAR-Packaged Software
This section shows you how to invoke and run applets and applications that are packaged in JAR files.
Additional References
The documentation for the JDK includes reference pages for the Jar tool:
Как открывать, редактировать и конвертировать файлы JAR
Файлы JAR сжаты в ZIP и часто хранят такие вещи, как файлы CLASS, файлы манифеста и ресурсы приложения, такие как изображения, звуковые клипы и сертификаты безопасности. Так как они могут хранить сотни или даже тысячи файлов в сжатом формате, легко обмениваться файлами JAR и перемещать их.
Мобильные устройства с поддержкой Java могут использовать файлы JAR в качестве файлов игры, а некоторые веб-браузеры содержат темы и надстройки в формате JAR.
Как открыть файлы JAR
Некоторые мобильные устройства имеют встроенную JRE. После установки приложения Java также можно открывать в веб-браузере, например Firefox, Safari, Edge или Internet Explorer ( но не в Chrome ).
Поскольку вам могут потребоваться разные программы для открытия разных файлов JAR, см. Как изменить программу по умолчанию для определенного расширения файла в Windows, если она автоматически открывается в программе, с которой вы не хотите ее использовать.
Ошибки открытия файлов JAR
Из-за настроек безопасности в операционной системе Windows и в некоторых веб-браузерах, весьма часто можно увидеть ошибки при попытке доступа к приложениям Java.
Как конвертировать файл JAR
Преобразование приложения Java для использования на платформе Android потребует преобразования файла JAR в APK. Одним из вариантов может быть запуск файла JAR в эмуляторе Android, чтобы программа автоматически создала файл APK. Однако, кажется, что самый простой способ получить Java-программу на Android — просто скомпилировать APK из исходного исходного кода.
Файлы WAR являются файлами Java Web Archive, но вы не можете преобразовать файл JAR напрямую в файл WAR, поскольку формат WAR имеет особую структуру, которой нет в JAR. Вместо этого вы можете создать WAR-файл и затем добавить JAR-файл в каталог lib, чтобы классы внутри JAR-файла были доступны для использования. WizToWar может помочь вам сделать это.