Работаем с JAR-архивами.
Иногда возникает потребность в том, чтобы java-программа могла просмотреть содержимое jar-архива, и извлечь его. В Интернете мне не удалось найти много информации по этому вопросу. Хотя, если честно, я не очень-то и искал. Поэтому, решил разобраться во всём сам. Пошарив по документации, мне в голову пришли следующие мысли. Если мы заранее знаем, что именно нам нужно извлечь из jar-файла, это не составит особого труда.
- Для начала нам нужно создать объект класса java.util.jar.JarFile (далее JarFile), и указать для него имя просматриваемого jar-файла.
- Затем, создаём объект класса java.util.jar.JarEntry (далее JarEntry) и указываем для него имя файла, который необходимо извлечь.
- Для объекта JarFile создаём поток ввода с помощью метода getInputStream(). В качестве аргумента передадим ему объект JarEntry.
- Ну а далее, работаем с потоками стандартным образом, используя методы read() и write().
У нас должно получиться что-то вроде:
JarFile jarFile = new JarFile ( «some_jar_file.jar» ) ;
JarEntry jarEntry = new JarEntry ( «something.smth» ) ;
InputStream in = jarFile.getInputStream ( jarEntry ) ;
FileOutputStream out = new FileOutputStream ( jarEntry.getName ()) ;
int t;
while (( t = in.read ()) != — 1 )
out.write ( t ) ;
Конечно же не забываем включить обработку исключения IOException. Не правда ли, элементарно? Но что делать, если мы не знаем, что содержится в jar-архиве? Подумав немного над этим вопросом, я ознакомился с классом ZipFile. Ведь JarFile является его наследником. У класса ZipFile есть метод entries(), который возвращает объект интерфейса Enumeration, содержащий имена всех файлов, входящих в архив. Но так как пользоваться этим объектом, мягко говоря, неудобно, то имеет смысл перенести всё содержимое в объект класса Vector. Получаем что-то типа:
Enumeration entries;
Vector v;
int vc= 0 ;
/*
* Vector capacity – количество элементов в векторе v. Почему-то, метод
* v.capacity() выдаёт большее число, чем на самом деле. Разбираться с этим не
* стал 🙂
*/
entries=jarFile.entries () ;
while ( entries.hasMoreElements ()) vect.add ( entries.nextElement ()) ;
vc++;
>
Замечу сразу, что я писал программу для Java 1.5. Для Java 1.4 и более ранних версий работа с объектами Enumeration и Vector была бы немного другой, немного более трудной. Спасибо Sun Microsystems за облегчение и без того тяжкой участи программистов! 🙂 Ну а теперь, имея список содержимого jar-архива, мы спокойно можем распаковывать его, не забывая создавать подкаталоги, содержащиеся в архиве. Для этого используем метод mkdir() класса File. Назовём наш метод extract(). Он может иметь следующий вид:
public void extract () <
File tmpfile;
/*
* создаём временный объект, который будет создавать каталоги
*/
JarEntry tmpentry; /* создаём временную ссылку на файл в архиве */
FileOutputStream out; /* это и так понятно */
InputStream in; /* и это тоже */
int t; /* переменная для копирования файла */
try <
/*
* создаём цикл для извлечения файлов из архива. Вот нам и пригодилась
* переменная vc
*/
for ( int i = 0 ; i ) <
/*
* берём из вектора имя очередного файла или каталога
*/
tmpentry = vect.get ( i ) ;
tmpfile = new File ( tmpentry.getName ()) ;
/* если tmpfile – каталог, */
if ( tmpentry.isDirectory ()) <
/* то создаём его */
if ( !tmpfile.mkdir ()) <
System.out.println ( «Can’t create directory: »
+ tmpfile.getName ()) ;
/*
* если он не создаётся,
*/
return ; /* выходим из функции */
>
>
/*
* ну а если tmpfile – не каталог, а файл, то спокойно извлекаем его
*/
else <
in = jarFile.getInputStream ( tmpentry ) ;
out = new FileOutputStream ( tmpfile ) ;
while (( t = in.read ()) != — 1 )
out.write ( t ) ;
/*
* лучше потоки ввода и вывода закрывать, иначе наша программа
*/
out.close () ;
/*
* может не сосем корректно работать (некоторые файлы могут
* теряться)
*/
in.close () ;
>
>
>
/* обрабатываем исключение */
catch ( IOException e ) <
System.out.println ( e.getMessage ()) ;
e.printStackTrace () ; /* это, по-моему, не совсем обязательно */
System.exit ( 0 ) ;
>
>
Ура товарищи, мы это сделали! Аналогичным образом можно работать и с zip-архивами. Необходимо только поменять JarFile и JarEntry на ZipFile и ZipEntry соответственно. На основе этого можно сделать что-нибудь более сложное и подходящее под какие-то конкретные цели. Алгоритм может быть и более оптимально построен. В статье он не совсем оптимален для пущей наглядности.
How to Extract a JAR File
This article was co-authored by wikiHow staff writer, Darlene Antonelli, MA. Darlene Antonelli is a Technology Writer and Editor for wikiHow. Darlene has experience teaching college courses, writing technology-related articles, and working hands-on in the technology field. She earned an MA in Writing from Rowan University in 2012 and wrote her thesis on online communities and the personalities curated in such communities.
The wikiHow Tech Team also followed the article’s instructions and verified that they work.
This article has been viewed 809,207 times.
JAR (.jar) files are archive files that contain Java class and associated metadata and resources. They are built on the ZIP format. [1] X Research source They are typically executed within a Java environment, but they can also be opened using archive programs like WinZIP, WinRAR, and 7-Zip. This wikiHow teaches you how to extract a JAR file’s contents.
- Since JAR files work like ZIP files, you can use an archive program like WinRAR to extract them.
- For Windows users, you can install Java SE to use the ‘jar’ extraction command in the Command Prompt.
- If you’re a macOS user, you can also install and use Java SE. You’ll use the ‘jar’ command in the Terminal.
Using an Archiving App
Install an archive program. JAR files work just like ZIP files. You can use any archive program to extract them. On Windows, you can Install WinRAR 7-Zip, or WinZIP. Macs have their own built-in archive program called Archive Utility. [2] X Research source
Find the JAR file you want to extract. Use File Explorer (press Win + E to open File Explorer) or Finder on Mac to navigate to the JAR file you want to extract.
- If you don’t see this option, click the JAR file once, then right-click it again and select Open with.
Click Extract files or Extract here . «Extract files» gives you the option to select a destination to extract the file to. «Extract here» extracts the files to the same location the Jar file is located.
Select an extraction location. If necessary, click one of the folders on the right side of the window to select it as the location to which you want to extract your JAR file (WinRAR). If you are using 7-Zip, click the icon with three dots in the upper-right corner and navigate to the folder you want to extract the files to. Then click Ok.
Click OK . It’s at the bottom of the WinRAR window. Doing so will extract your JAR file to the selected folder.
Using Java on Windows
- Open the JDK download page.
- Click the Windows tab.
- Scroll down and click «https://download.oracle.com/java/17/latest/jdk-17_windows-x64_bin.exe» next to «Windows x64 Installer».
- Click the checkbox next to agree to the license agreement and click the green download button.
- Open the JDK install file and click Yes.
- Click Next.
- Click Close.
. Click the folder-shaped File Explorer app icon in the taskbar that’s at the bottom of your computer’s screen.
Select the JAR file’s path. Click a blank space in the address bar at the top of the File Explorer window to do so.
Navigate to the JAR file’s path location. To do this type in cd and press the space bar. Then press Ctrl+V to past the file’s path. Then press «Enter»..
- If you receive an error message that says «‘jar’ is not recognized as an external or internal command», you need to change the path environment variable to «C:\Program Files\Java\jdk[latest version]\bin» Make sure you replace «[latest version]» with the latest version of Java Development Kit you have installed.
Using Java on a Mac
- Open the JDK download page.
- Click the macOS tab.
- Scroll down and click «https://download.oracle.com/java/17/latest/jdk-17_macos-x64_bin.dmg» next to «macOS Installer».
- Open the JDK dmg file.
- Double-click the JDK pkg file.
- Click Continue
- Click Install.
- Enter your Mac user password and click Install Software.
- Click Close
. Type «terminal» into the Spotlight text box, then double-click the Terminal icon when it appears. This will open a Terminal window.
Type in jar xf and press the space bar. This is the command to extract a JAR file. Don’t press enter just yet, there is still more you need to do.
Press ⌘ Command + V to paste in your JAR file’s path, and press ⏎ Return . This executes the command to extract the JAR file.
Community Q&A
I receive an error that jar is not recognized as an internal or external command, operable program or batch file. What do I need to do?
You will need to make sure that the Java JDK is installed. Windows also requires for your environment variables to have a path set to the location of the jar executable. Check your Path Environment Variable under the Advanced System Settings in the Settings Window. Restart your computer when you make changes to your path.
Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow
I got an error that said java.io.FileNotFoundException (The system cannot find the file specified). What’s up?
Extract jar with java
- The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
- Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
- A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
- Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
- How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
- GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
- 4 popular machine learning certificates to get in 2023 AWS, Google, IBM and Microsoft offer machine learning certifications that can further your career. Learn what to expect from each.
- Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
- 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
- 5 steps to approach BYOD compliance policies It can be difficult to ensure BYOD endpoints are compliant because IT can’t configure them before they ship to users. Admins must.
- Coveware: Rate of victims paying ransom continues to plummet Incident response firm Coveware said 34% of ransomware victims paid the ransom in Q2 2023, a sharp decline from last quarter and .
- Mandiant: JumpCloud breach led to supply chain attack Mandiant researchers attribute the supply chain attack to a North Korean threat actor that abused JumpCloud’s commands framework .
- AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
- Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
- Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .