Java zip на телефон

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Android Java wrapper for 7z archiver engine

License

LGPL-2.1, Unknown licenses found

Licenses found

omicronapps/7-Zip-JBinding-4Android

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Android Java wrapper for 7z archiver engine

Android library version of 7-Zip-JBinding java wrapper.

Native (JNI) cross-platform library to extract (password protected, multi-part) 7z Arj BZip2 Cab Chm Cpio Deb GZip HFS Iso Lzh Lzma Nsis Rar Rpm Split Tar Udf Wim Xar Z Zip archives and create 7z, Zip, Tar, GZip & BZip2 from Java on Android.

All features of 7-Zip-JBinding supported:

  • Very fast extraction of many archive formats out of Java
  • Compress 7z, Zip, Tar, GZip, BZip2
  • Extract password protected archives
  • Extract splitted into volumes archives
  • Extract multiple archives multithreaded
  • 8599 JUnit tests
  • Cross-platform

7-Zip was created by Igor Pavlov (7-Zip Web Site), with 7-Zip-JBinding initially designed and implemented by Boris Brodski (7-Zip-JBinding Web Site). 7-Zip-JBinding was adapted for Android by Fredrik Claesson.

7-Zip-JBinding-4Android is currently not available on JCenter due to package name conflict with the 7-Zip-JBinding JAR library. However, it is possible to import the AAR library in Gradle from the JitPack repository.

  1. Add the JitPack repository to project level build.gradle file (example: MyAndroidProject/build.gradle )
  1. Sync project
  2. SevenZip should now be possible to use by importing net.sf.sevenzipjbinding.SevenZip

Examples of opening an existing archive, along with listing and extracting the contents are provided below.

Note that the SevenZip class provides static access and need not be instantiated. In addition, the native library will be automatically by calling any of the openInArchive() variants or getSevenZipVersion() .

7-zip and 7-Zip-JBinding versions can be retrieved as follows. Note that calling getSevenZipVersion() will result in the native library being loaded, following which isInitializedSuccessfully() should return true if successful.

import android.util.Log; import net.sf.sevenzipjbinding.SevenZip; public class TestVersion < private static final String TAG = "TestVersion"; public void testVersion() < SevenZip.Version version = SevenZip.getSevenZipVersion(); Log.i(TAG, "7-zip version: " + version.major + "." + version.minor + "." + version.build + " (" + version.version + "), " + version.date + version.copyright); Log.i(TAG, "7-Zip-JBinding version: " + SevenZip.getSevenZipJBindingVersion()); Log.i(TAG, "Native library initialized: " + SevenZip.isInitializedSuccessfully()); >> 

Open an existing archive with openInArchive() , providing an IInStream instance for access to the file archive, and an IArchiveOpenCallback instance for archive open status callbacks. Here openInArchive() will return an IInArchive instance through which the archive can be queried.

import android.util.Log; import net.sf.sevenzipjbinding.ArchiveFormat; import net.sf.sevenzipjbinding.IArchiveOpenCallback; import net.sf.sevenzipjbinding.IInArchive; import net.sf.sevenzipjbinding.PropID; import net.sf.sevenzipjbinding.SevenZip; import net.sf.sevenzipjbinding.SevenZipException; import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class TestList < private static final String TAG = "TestList"; public void testList(File file) < try < RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); RandomAccessFileInStream inStream = new RandomAccessFileInStream(randomAccessFile); ArchiveOpenCallback callback = new ArchiveOpenCallback(); IInArchive inArchive = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP, inStream, callback); ArchiveFormat format = inArchive.getArchiveFormat(); Log.i(TAG, "Archive format: " + format.getMethodName()); int itemCount = inArchive.getNumberOfItems(); Log.i(TAG, "Items in archive: " + itemCount); for (int i = 0; i < itemCount; i++) < Log.i(TAG, "File " + i + ": " + inArchive.getStringProperty(i, PropID.PATH) + " : " + inArchive.getStringProperty(i, PropID.SIZE)); >inArchive.close(); inStream.close(); > catch (FileNotFoundException e) < Log.e(TAG, e.getMessage()); >catch (SevenZipException e) < Log.e(TAG, e.getMessage()); >catch (IOException e) < Log.e(TAG, e.getMessage()); >> private class ArchiveOpenCallback implements IArchiveOpenCallback < @Override public void setTotal(Long files, Long bytes) < Log.i(TAG, "Archive open, total work: " + files + " files, " + bytes + " bytes"); >@Override public void setCompleted(Long files, Long bytes) < Log.i(TAG, "Archive open, completed: " + files + " files, " + bytes + " bytes"); >> > 

File extraction, standard interface

Files can be extracted through IInArchive.extract() method. This requires providing an IArchiveExtractCallback implementation in order to receive status callbacks and for providing an ISequentialOutStream instance. Here the ISequentialOutStream will receive the extracted data through write() callbacks.

import android.util.Log; import net.sf.sevenzipjbinding.ArchiveFormat; import net.sf.sevenzipjbinding.ExtractAskMode; import net.sf.sevenzipjbinding.ExtractOperationResult; import net.sf.sevenzipjbinding.IArchiveExtractCallback; import net.sf.sevenzipjbinding.IArchiveOpenCallback; import net.sf.sevenzipjbinding.IInArchive; import net.sf.sevenzipjbinding.ISequentialOutStream; import net.sf.sevenzipjbinding.SevenZip; import net.sf.sevenzipjbinding.SevenZipException; import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class TestExtract < private static final String TAG = "TestExtract"; public void testExtract(File file) < try < RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); RandomAccessFileInStream inStream = new RandomAccessFileInStream(randomAccessFile); ArchiveOpenCallback callback = new ArchiveOpenCallback(); IInArchive inArchive = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP, inStream, callback); ArchiveExtractCallback extractCallback = new ArchiveExtractCallback(); inArchive.extract(null, false, extractCallback); inArchive.close(); inStream.close(); >catch (FileNotFoundException e) < Log.e(TAG, e.getMessage()); >catch (SevenZipException e) < Log.e(TAG, e.getMessage()); >catch (IOException e) < Log.e(TAG, e.getMessage()); >> private class ArchiveOpenCallback implements IArchiveOpenCallback < @Override public void setTotal(Long files, Long bytes) < Log.i(TAG, "Archive open, total work: " + files + " files, " + bytes + " bytes"); >@Override public void setCompleted(Long files, Long bytes) < Log.i(TAG, "Archive open, completed: " + files + " files, " + bytes + " bytes"); >> private class ArchiveExtractCallback implements IArchiveExtractCallback < @Override public ISequentialOutStream getStream(int index, ExtractAskMode extractAskMode) throws SevenZipException < Log.i(TAG, "Extract archive, get stream: " + index + " to: " + extractAskMode); SequentialOutStream stream = new SequentialOutStream(); return stream; >@Override public void prepareOperation(ExtractAskMode extractAskMode) throws SevenZipException < Log.i(TAG, "Extract archive, prepare to: " + extractAskMode); >@Override public void setOperationResult(ExtractOperationResult extractOperationResult) throws SevenZipException < Log.i(TAG, "Extract archive, completed with: " + extractOperationResult); if (extractOperationResult != ExtractOperationResult.OK) < throw new SevenZipException(extractOperationResult.toString()); >> @Override public void setTotal(long total) throws SevenZipException < Log.i(TAG, "Extract archive, work planned: " + total); >@Override public void setCompleted(long complete) throws SevenZipException < Log.i(TAG, "Extract archive, work completed: " + complete); >> private class SequentialOutStream implements ISequentialOutStream < @Override public int write(byte[] data) throws SevenZipException < if (data == null || data.length == 0) < throw new SevenZipException("null data"); >Log.i(TAG, "Data to write: " + data.length); return data.length; > > > 

Slow extraction, standard interface

Alternatively, the slow extraction interface can be used through IInArchive.extractSlow() , which however requires accessing each file individually.

import android.util.Log; import net.sf.sevenzipjbinding.ArchiveFormat; import net.sf.sevenzipjbinding.ExtractOperationResult; import net.sf.sevenzipjbinding.IArchiveOpenCallback; import net.sf.sevenzipjbinding.IInArchive; import net.sf.sevenzipjbinding.ISequentialOutStream; import net.sf.sevenzipjbinding.SevenZip; import net.sf.sevenzipjbinding.SevenZipException; import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class TestSlowExtract < private static final String TAG = "TestSlowExtract"; public void testSlowExtract(File file) < try < RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); RandomAccessFileInStream inStream = new RandomAccessFileInStream(randomAccessFile); ArchiveOpenCallback callback = new ArchiveOpenCallback(); IInArchive inArchive = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP, inStream, callback); int itemCount = inArchive.getNumberOfItems(); SequentialOutStream outStream = new SequentialOutStream(); for (int i = 0; i < itemCount; i++) < ExtractOperationResult result = inArchive.extractSlow(i, outStream); if (result != ExtractOperationResult.OK) < Log.e(TAG, result.toString()); >> inArchive.close(); inStream.close(); > catch (FileNotFoundException e) < Log.e(TAG, e.getMessage()); >catch (SevenZipException e) < Log.e(TAG, e.getMessage()); >catch (IOException e) < Log.e(TAG, e.getMessage()); >> private class ArchiveOpenCallback implements IArchiveOpenCallback < @Override public void setTotal(Long files, Long bytes) < Log.i(TAG, "Archive open, total work: " + files + " files, " + bytes + " bytes"); >@Override public void setCompleted(Long files, Long bytes) < Log.i(TAG, "Archive open, completed: " + files + " files, " + bytes + " bytes"); >> private class SequentialOutStream implements ISequentialOutStream < @Override public int write(byte[] data) throws SevenZipException < if (data == null || data.length == 0) < throw new SevenZipException("null data"); >Log.i(TAG, "Data to write: " + data.length); return data.length; > > > 

Main features of 16.02-2.02 (Release, cross-platform, based on zip/p7zip 16.02)

Main features of 16.02-2.01 (Release, extraction/compression/update, cross-platform, based on zip/p7zip 16.02)

  • Bind 7-Zip 16.02, In-memory archive extraction/creation/update
  • Extraction of
    • 7z, Arj, BZip2, Cab, Chm, Cpio, Ar/A/Lib/Deb, Fat, GZip, HFS, Iso, Lzh, Lzma, Nsis, Ntfs, Rar, Rpm, Split, Tar, Udf, Wim, Xar, Z, Zip
    • Archive format auto detection
    • Support for password protected and in volumes splitted archives
    • Full featured and simplified extraction interfaces
    • 7z, Zip, Tar, GZip, BZip2
    • Convenient archive format specific and generic compression APIs
    • Password protected archives (7z, zip) with encrypted archive headers (7z only)
    • Initialization
    • All extraction methods
    • Compression
    • Unicode support

    Main features of 9.20-2.00beta (Release candidate, extraction/compression/update, cross-platform, based on zip/p7zip 9.20)

    • Extraction of
      • 7z, Arj, BZip2, Cab, Chm, Cpio, Deb, GZip, HFS, Iso, Lzh, Lzma, Nsis, Rar, Rpm, Split, Tar, Udf, Wim, Xar, Z, Zip
      • Archive format auto detection
      • Support for password protected and volumed archives
      • Simple extraction interface
      • 7z, Zip, Tar, GZip, BZip2
      • Archive format specific or generic compression API
      • 7z, Zip, Tar, Rar, Lzma, Iso, GZip, Cpio, BZIP2, Z, Arj, Lzh, Cab, Chm, Nsis, DEB, RPM, UDF

      Источник

      Работа с архивами Zip и 7z

      В мобильной разработке бывает потребность сделать приложение для работы без интернета. Например, словарь или справочник, который будет использоваться в суровых полевых условиях. Тогда для работы приложения нужно единожды выкачать архив с данными и сохранить его у себя. Сделать это можно посредством запроса в сеть, но так же можно зашить архив с данными внутрь приложения.

      Согласно требованиям Google Play, apk-файл приложения должен быть не более 50 МБ, так же можно прикрепить два файла дополнения .obb по 2 гигабайта. Механизм простой, но сложный при эксплуатации, поэтому лучше всего уложиться в 50 МБ и возрадоваться. И в этом нам помогут целых два архивных формата Zip и 7z.

      Давайте рассмотрим их работу на примере уже готового тестового приложения ZipExample.

      Для тестов была создана sqlite база данных test_data.db. Она содержит 2 таблицы android_metadata — по традиции и my_test_data с миллионом строчек:

      Размер полученного файла составляет 198 МБ.

      Сделаем два архива test_data.zip (10.1 МБ) и test_data.7z (3.05 МБ).

      Как очевидно, файлы БД sqlite очень хорошо сжимаются. По опыту могу сказать, что чем проще структура базы, тем лучше сжимается. Оба этих файла располагаются в папке assets и в процессе работы будут разархивированы.

      Внешний вид программы представляет собой окно с текстом и двумя кнопками:

      Вот метод распаковки zip архива:

       public void onUnzipZip(View v) throws IOException < SimpleDateFormat sdf = new SimpleDateFormat(" HH:mm:ss.SSS"); String currentDateandTime = sdf.format(new Date()); String log = mTVLog.getText().toString() + "\nStart unzip zip" + currentDateandTime; mTVLog.setText(log); InputStream is = getAssets().open("test_data.zip"); File db_path = getDatabasePath("zip.db"); if (!db_path.exists()) db_path.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(db_path); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); ZipEntry ze; while ((ze = zis.getNextEntry()) != null) < byte[] buffer = new byte[1024]; int count; while ((count = zis.read(buffer)) >-1) < os.write(buffer, 0, count); >os.close(); zis.closeEntry(); > zis.close(); is.close(); currentDateandTime = sdf.format(new Date()); log = mTVLog.getText().toString() + "\nEnd unzip zip" + currentDateandTime; mTVLog.setText(log); > 

      Распаковывающим классом тут является ZipInputStream он входит в пакет java.util.zip, а тот в свою очередь в стандартную Android SDK и поэтому работает «из коробки» т.е. ничего отдельно закачивать не надо.

      Вот метод распаковки 7z архива:

      public void onUnzip7Zip(View v) throws IOException < SimpleDateFormat sdf = new SimpleDateFormat(" HH:mm:ss.SSS"); String currentDateandTime = sdf.format(new Date()); String log = mTVLog.getText().toString() + "\nStart unzip 7zip" + currentDateandTime; mTVLog.setText(log); File db_path = getDatabasePath("7zip.db"); if (!db_path.exists()) db_path.getParentFile().mkdirs(); SevenZFile sevenZFile = new SevenZFile(getAssetFile(this, "test_data.7z", "tmp")); SevenZArchiveEntry entry = sevenZFile.getNextEntry(); OutputStream os = new FileOutputStream(db_path); while (entry != null) < byte[] buffer = new byte[8192];// int count; while ((count = sevenZFile.read(buffer, 0, buffer.length)) >-1) < os.write(buffer, 0, count); >entry = sevenZFile.getNextEntry(); > sevenZFile.close(); os.close(); currentDateandTime = sdf.format(new Date()); log = mTVLog.getText().toString() + "\nEnd unzip 7zip" + currentDateandTime; mTVLog.setText(log); > 
       public static File getAssetFile(Context context, String asset_name, String name) throws IOException < File cacheFile = new File(context.getCacheDir(), name); try < InputStream inputStream = context.getAssets().open(asset_name); try < FileOutputStream outputStream = new FileOutputStream(cacheFile); try < byte[] buf = new byte[1024]; int len; while ((len = inputStream.read(buf)) >0) < outputStream.write(buf, 0, len); >> finally < outputStream.close(); >> finally < inputStream.close(); >> catch (IOException e) < throw new IOException("Could not open file" + asset_name, e); >return cacheFile; > 

      Сначала мы копируем файл архива из asserts , а потом разархивируем при помощи SevenZFile . Он находится в пакете org.apache.commons.compress.archivers.sevenz; и поэтому перед его использованием нужно прописать в build.gradle зависимость: compile ‘org.apache.commons:commons-compress:1.8’.
      Android Stuodio сама скачает библиотеки, а если они устарели, то подскажет о наличии обновления.

      Вот экран работающего приложения:

      Размер отладочной версии приложения получился 6,8 МБ.
      А вот его размер в устройстве после распаковки:

      Внимание вопрос кто в черном ящике что в кеше?

      В заключении хочу сказать, что распаковка архивов занимает продолжительное время и поэтому нельзя его делать в основном (UI) потоке. Это приведет к подвисанию интерфейса. Во избежание этого можно задействовать AsyncTask , а лучше фоновый сервис т.к. пользователь может не дождаться распаковки и выйти, а вы получите ошибку (правда если не поставите костылей в методе onPostExecute).

      Буду рад конструктивной критике в комментариях.

      Источник

      Java zip на телефон

      Мое устройство

      Поиск по категориям
      • Базы данных
      • Бизнес & Профессия
      • Здоровье & Медицина
      • Игры
      • Интернет & Коммуникации
      • Мультимедиа & Графика
      • Наука & Образование
      • Программирование & Разработка
      • Словари & Переводчики
      • Темы & Обои & Скины
      • Туризм & Навигация
      • Управление задачами и временем
      • Утилиты
      • Антивирусы
      • Архиваторы
      • Батарея
      • Безопасность
      • Инсталляторы
      • Интерфейс
      • Клавиатуры
      • Локализация
      • Лончеры & Диспетчеры задач
      • Менеджеры паролей
      • Поиск
      • Профили
      • Работа с памятью & Бекапы
      • Работа с текстом
      • Реестр
      • Синхронизация
      • Системные
      • Скринсэйверы
      • Скриншоты
      • Тесты & Бенчмарки
      • Удаленное управление & Пульты
      • Файл менеджеры
      • Хаки & Твики
      • Хранение и шифрование данных
      • Штрих коды
      • Экран & Подсветка
      • Эмуляторы & Оболочки
      • Другие
      • Финансы
      • Хобби & Развлечения
      • Чтение

      Zip Utility 2

      Это программное обеспечение Java позволяет создавать, а также извлечение архивных файлов на себя ваши телефоны. Созданный с использованием.

      Источник

      Читайте также:  Php reverse proxy apache
Оцените статью