Мое приложение загружает zip-файл с сервера, извлекает этот zip-файл и сохраняет файлы на SD-карту, но проблема в том, что я загружаю zip-файлы размером 4-5 МБ и извлекаю их , это работает хорошо, но если я загружаю zip-файл размером 30-35 МБ, это приведет к ошибке, извините за мое плохое общение на английском.
Ниже приведен мой код для загрузки и распаковки zip-файла: —
открытый класс UnzipManager {частный статический String BASE_FOLDER; общедоступный статический контекст localContext; общедоступный статический String passurl; публичный статический счетчик int; общедоступный статический контекст Context; /* * Вы можете использовать этот флаг, чтобы проверить, работает ли Unzippingthread. */Public static boolean isDownloadInProgress; /* * После разархивирования с использованием этого флага вы можете проверить, возникли ли какие-либо исключения из-за нехватки памяти * или нет ... и, соответственно, предупредить пользователя .. */public static boolean isLowOnMemory; общедоступный статический int i = 0; общедоступный статический ZipEntry zipEntry; общедоступный статический void startUnzipping (Context ctx, int c, String url) {context = ctx; count = c; /* * УБЕДИТЕСЬ, ЧТО ПЕРЕМЕННАЯ localContext БЫЛА ИНИЦИАЛИЗИРОВАНА ДО * ВЫЗОВА ЭТОГО МЕТОДА. * * ТАКЖЕ УБЕДИТЕСЬ, ЧТО ВЫ УСТАНОВИЛИ «ИНТЕРНЕТ» И «СОСТОЯНИЕ ДОСТУПА К СЕТИ» * РАЗРЕШЕНИЯ В ФАЙЛЕ МАНИФЕСТА ПРИЛОЖЕНИЯ. */Log.d ("DEBUG", "In startUnzipping ()"); UnzipManager.BASE_FOLDER = Environment.getExternalStorageDirectory () + File.separator + «образцы»; /* * */Log.d ("DEBUG", "BASE_FOLDER:" + UnzipManager.BASE_FOLDER); UnzipManager.isLowOnMemory = false; //Начинаем распаковку в потоке ... что безопаснее//для дорогостоящих процессов .. passurl = url; новый UnzipThread (). start (); } частный статический класс UnzipThread расширяет поток {@Override public void run () {UnzipManager.isDownloadInProgress = true; Log.d ("DEBUG", "Распаковка ----------------------------"); URLConnection urlConnection; пытаться {/*********************************************** * * * ЕСЛИ вы распаковываете заархивированный файл, сохраните его по некоторому URL-адресу на * удаленном сервере * ****************************** ***************/URL finalUrl = новый URL (passurl/* строка URL, в которой хранится заархивированный файл ... */); urlConnection = finalUrl.openConnection (); //Получить размер входящего потока (сжатого файла) с//сервера .. int contentLength = urlConnection.getContentLength (); Log.d ("ОТЛАДКА", "urlConnection.getContentLength ():" + contentLength); /*********************************************** **** * * ВЫ МОЖЕТЕ ПОЛУЧИТЬ ВХОДНОЙ ПОТОК ЗАПИСАННОГО ФАЙЛА ИЗ ПАПКИ АКТИВОВ * А ТАКЖЕ ... В ЭТОМ СЛУЧАЕ ПРОСТО ПРОЙДИТЕ ЭТО ВХОДНАЯ КОМАНДА * ЗДЕСЬ ... УБЕДИТЕСЬ, ЧТО ВЫ УСТАНОВИЛИ ДЛИНУ СОДЕРЖИМОГО ПОТОКА ОДНОЙ ДЛИНЫ. . * ********************************************** ******/ZipInputStream zipInputStream = новый ZipInputStream (urlConnection.getInputStream ()); /* * Перебрать все файлы и папки */for (zipEntry = zipInputStream.getNextEntry (); zipEntry! = Null; zipEntry = zipInputStream .getNextEntry ()) {Журнал. d ("DEBUG", "Извлечение:" + zipEntry.getName () + "..."); /* * Извлеченный файл будет сохранен с тем же именем, что и в * заархивированной папке. */String innerFileName = BASE_FOLDER + File.separator + zipEntry.getName (); Файл innerFile = новый файл (innerFileName); /* * Проверка наличия файла и выполнение * необходимых действий */if (innerFile.exists ()) {Log.d ("DEBUG", "Запись уже завершена !, поэтому удаление .."); innerFile.delete (); }/* * Проверка извлеченной записи для типа папки ... и выполнение * необходимых действий */if (zipEntry.isDirectory ()) {Log.d ("DEBUG", "Запись - это каталог .."); innerFile.mkdirs (); } else {Log.d ("DEBUG", "Запись - это файл .."); FileOutputStream outputStream = новый FileOutputStream (innerFileName); финальный int BUFFER_SIZE = 2048; /* * Получить буферизованный выходной поток .. */BufferedOutputStream bufferedOutputStream = new BufferedOutputStream (outputStream, BUFFER_SIZE); /* * Запись в буферизованный выходной поток файла, .. */int count = 0; байт [] буфер = новый байт [BUFFER_SIZE]; while ((count = zipInputStream.read (буфер, 0, BUFFER_SIZE))! = -1) {bufferedOutputStream.write (буфер, 0, счетчик); }/********************************************* * ЕСЛИ ВЫ ХОТИТЕ ОТСЛЕЖИВАТЬ НЕТ ЗАГРУЖЕННЫХ ФАЙЛОВ, ИМЕЙТЕ * СТАТИЧЕСКУЮ ПЕРЕМЕННУЮ СЧЕТЧИК, ИНИЦИАЛИЗИРУЙТЕ ЕГО В * startUnzipping () перед вызовом startUnZipping () И * УВЕЛИЧИВАЙТЕ ПЕРЕМЕННУЮ СЧЕТЧИК ЗДЕСЬ ... ПОЗЖЕ * МОЖЕТЕ ИСПОЛЬЗОВАТЬ ЗНАЧЕНИЕ ЗНАЧЕНИЯ ПЕРЕКЛЮЧИТЕ ПРОВЕРЬТЕ, ВСЕ ЛИ ЗАЖИГОВАННЫЕ ФАЙЛЫ РАЗРЕЖИНЫ И СОХРАНЕНЫ НАДЛЕЖАЩИМ ИЛИ НЕТ. * * *********************************************** *//* * Обработка закрытия выходных потоков .. */bufferedOutputStream.flush (); bufferedOutputStream.close (); }/* * Завершить текущий zipEntry */zipInputStream.closeEntry (); }/* * Обработка закрытия входного потока ... */zipInputStream.close (); Log.d ("ОТЛАДКА", "--------------------------------"); Log.d ("DEBUG", "Распаковка завершена .."); я = 1; } catch (IOException e) {Log.d ("DEBUG", "Произошло исключение:" + e.getMessage ()); if (e.getMessage (). equalsIgnoreCase («На устройстве не осталось места»)) {UnzipManager.isLowOnMemory = true; } e.printStackTrace (); } MainActivity.pd.dismiss (); ((MainActivity) контекст) .finish (); UnzipManager.isDownloadInProgress = false; }};}
Ошибка Logcat: —
02-17 12: 21: 16.835: D/DEBUG (20562 ): Произошло исключение:/mnt/sdcard/samples/iPhone_zendura_Q4a/0.png (Нет такого файла или каталога) 02-17 12:21: 16.835: W/System.err (20562): java.io.FileNotFoundException:/mnt /sdcard/samples/iPhone_zendura_Q4a/0.png (Нет такого файла или каталога) 02-17 12: 21: 16.906: W/System.err (20562): в org.apache.harmony.luni.platform.OSFileSystem.open ( Собственный метод) 02-17 12: 21: 16.906: W/System.err (20562): в dalvik.system.BlockGuard $ WrappedFileSystem.open (BlockGuard.java:232) 02-17 12:21: 16.906: W/System .err (20562): в java.io.FileOutputStream. (FileOutputStream. java: 94) 02-17 12:21: 16.906: W/System.err (20562): в java.io.FileOutputStream. (FileOutputStream.java:165)02-17 12:21: 16.906: W/ System.err (20562): в java.io.FileOutputStream. (FileOutputStream.java:144)02-17 12:21: 16.906: W/System.err (20562): в com.android.screens.UnzipManager $ UnzipThread.run (UnzipManager.java:129)
Я написал IntentService
, которые объединяют обе вещи вместе с прогрессом:
Добавьте следующий класс Service в ваше приложение (также объявите его в файле манифеста вашего приложения):
import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo ; импорт android.os.Bundle; импорт android.os.Handler; импорт android.os.Looper; импорт android.os.Parcel; импорт android.os.Parcelable; импорт android.os.ResultReceiver; импорт android.util.Log; импорт java.io.BufferedInputStream; импорт t java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile;/** * Создано Vaibhav.Jani 4.06.15. */открытый класс FileDownloadService расширяет IntentService {private static int STATUS_OK = 100; частный статический int STATUS_FAILED = 200; частная статическая финальная строка DOWNLOADER_RECEIVER = "downloader_receiver"; частная статическая финальная строка DOWNLOAD_DETAILS = "download_details"; приватная статическая финальная строка DOWNLOAD_STARTED = "download_started"; закрытая статическая конечная строка DOWNLOAD_FAILED = "download_failed"; закрытая статическая конечная строка DOWNLOAD_COMPLETED = "download_completed"; частная статическая финальная строка DOWNLOAD_PROGRESS = "download_progress"; общедоступный FileDownloadService () {супер (""); } @Override protected void onHandleIntent (намерение намерения) {Bundle bundle = intent.getExtras (); if (bundle == null ||! bundle.containsKey (DOWNLOADER_RECEIVER) ||! bundle.containsKey (DOWNLOAD_DETAILS)) {return; } ResultReceiver resultReceiver = bundle.getParcelable (DOWNLOADER_RECEIVER); DownloadRequest downloadDetails = bundle.getParcelable (DOWNLOAD_DETAILS); попробуйте {assert downloadDetails! = null; URL url = новый URL (downloadDetails.getServerFilePath ()); URLConnection urlConnection = url.openConnection (); urlConnection.connect (); int lengthOfFile = urlConnection.getContentLength (); Log.d ("FileDownloaderService", "Длина файла:" + lengthOfFile); downloadStarted (resultReceiver); InputStream input = новый BufferedInputStream (url.openStream ()); String localPath = downloadDetails.getLocalFilePath (); OutputStream output = новый FileOutputStream (localPath); байтовые данные [] = новый байт [1024]; длинный итог = 0; int count; в то время как ((count = input. читать (данные))! = -1) {всего + = счетчик; int progress = (int) ((всего * 100)/lengthOfFile); sendProgress (прогресс, resultReceiver); output.write (данные, 0, количество); } output.flush (); output.close (); input.close (); if (downloadDetails.isRequiresUnzip ()) {String unzipDestination = downloadDetails.getUnzipAtFilePath (); if (unzipDestination == null) {файл файл = новый файл (localPath); unzipDestination = file.getParentFile (). getAbsolutePath (); } распаковать (localPath, unzipDestination); } downloadCompleted (resultReceiver); if (downloadDetails.isDeleteZipAfterExtract ()) {Файл файл = новый файл (localPath); file.delete (); }} catch (исключение e) {e.printStackTrace (); downloadFailed (resultReceiver); }} public void sendProgress (int progress, получатель ResultReceiver) {Bundle progressBundle = new Bundle (); progressBundle.putInt (FileDownloadService.DOWNLOAD_PROGRESS, прогресс); Receiver.send (STATUS_OK, progressBundle); } public void downloadStarted (ResultReceiver resultReceiver) {Bundle progressBundle = new Bundle (); progressBundle.putBoolean (FileDownloadService.DOWNLOAD_STARTED, истина); resultReceiver.send (STATUS_OK, progressBundle); } public void downloadCompleted (ResultReceiver resultReceiver) {Bundle progressBundle = new Bundle (); progressBundle.putBoolean (FileDownloadService.DOWNLOAD_COMPLETED, истина); resultReceiver.send (STATUS_OK, progressBundle); } public void downloadFailed (ResultReceiver resultReceiver) {Bundle progressBundle = new Bundle (); progressBundle.putBoolean (FileDownloadService.DOWNLOAD_FAILED, истина); resultReceiver.send (STATUS_FAILED, progressBundle); } private void unzip (String zipFilePath, String unzipAtLocation) выдает исключение {File archive = new File (zipFilePath); попробуйте {ZipFile zipfile = new ZipFile (архив); for (Перечисление e = zipfile.entries (); e.hasMoreElements ();) {ZipEntry entry = (ZipEntry) e.nextElement (); unzipEntry (zipfile, запись, unzipAtLocation); }} catch (Exception e) {Log.e («Распаковать zip», «Разархивировать исключение», e); }} private void unzipEntry (ZipFile zipfile, ZipEntry entry, String outputDir) выдает исключение IOException {if (entry.isDirectory ()) {createDir (новый файл (outputDir, entry.getName ())); вернуть; } Файл outputFile = новый файл (outputDir, entry.getName ()); если (! outputFile.getParentFile (). exists ()) {createDir (outputFile.getParentFile ()); } Log.v ("ZIP E", "Извлечение:" + запись); InputStream zin = zipfile.getInputStream (запись); BufferedInputStream inputStream = новый BufferedInputStream (zin); BufferedOutputStream outputStream = новый BufferedOutputStream (новый FileOutputStream (outputFile)); попробуйте {//IOUtils.copy(inputStream, outputStream); попробуйте {для (int c = inputStream.read (); c! = -1; c = inputStream.read ()) {outputStream.write (c); }} наконец {outputStream.close (); }} наконец {outputStream.close (); inputStream.close (); }} private void createDir (файловый каталог) {if (dir.exists ()) {return; } Log.v ("ZIP E", "Создание каталога" + dir.getName ()); если (! dir. mkdirs ()) {выбросить новое исключение RuntimeException ("Невозможно создать каталог" + каталог); }} открытый статический класс FileDownloader расширяет ResultReceiver {private DownloadRequest downloadDetails; частный OnDownloadStatusListener onDownloadStatusListener; общедоступный статический FileDownloader getInstance (DownloadRequest downloadDetails, OnDownloadStatusListener downloadStatusListener) {Обработчик обработчика = новый обработчик (Looper.getMainLooper ()); FileDownloader fileDownloader = новый FileDownloader (обработчик); fileDownloader.downloadDetails = downloadDetails; fileDownloader.onDownloadStatusListener = downloadStatusListener; return fileDownloader; } публичная недействительная загрузка (контекст контекста) {если (isOnline (контекст)) {намерение намерения = новое намерение (контекст, FileDownloadService.class); intent.putExtra (FileDownloadService.DOWNLOADER_RECEIVER, это); intent.putExtra (FileDownloadService.DOWNLOAD_DETAILS, downloadDetails); context.startService (намерение); }} частный FileDownloader (обработчик обработчика) {super (обработчик); } @Override protected void onReceiveResult (int resultCode, Bundle resultData) {super.onReceiveResult (код результата, результатДанные); если (onDownloadStatusListener == null) {возврат; } if (resultCode == FileDownloadService.STATUS_OK) {if (resultData.containsKey (FileDownloadService.DOWNLOAD_STARTED) && resultData.getBoolean (FileDownloadService.DOWNLOAD_STARTED)) {onDownloadStatusListener. } else if (resultData.containsKey (FileDownloadService.DOWNLOAD_COMPLETED) && resultData.getBoolean (FileDownloadService.DOWNLOAD_COMPLETED)) {onDownloadStatusListener.onDownloadCompleted (); } иначе если (resultData.containsKey (FileDownloadService.DOWNLOAD_PROGRESS)) {int progress = resultData.getInt (FileDownloadService.DOWNLOAD_PROGRESS); onDownloadStatusListener.onDownloadProgress (прогресс); }} иначе, если (resultCode == FileDownloadService.STATUS_FAILED) {onDownloadStatusListener.onDownloadFailed (); }} общедоступный DownloadRequest getDownloadDetails () {return downloadDetails; } public void setDownloadDetails (DownloadRequest downloadDetails) {this.downloadDetails = downloadDetails; } общедоступный OnDownloadStatusListener getOnDownloadStatusListener () {return onDownloadStatusListener; } public void setOnDownloadStatusListener (OnDownloadStatusListener onDownloadStatusListener) {this.onDownloadStatusListener = onDownloadStatusListener; }} общедоступный статический интерфейс OnDownloadStatusListener {void onDownloadStarted (); void onDownloadCompleted (); void onDownloadFailed (); void onDownloadProgress (int progress); } открытый статический класс DownloadRequest реализует Parcelable {private String tag; частное логическое значение requiresUnzip; частная строка serverFilePath; private String localFilePath; частная строка unzipAtFilePath; частное логическое значение deleteZipAfterExtract = true; общедоступный DownloadRequest (String serverFilePath, String localPath) {this.serverFilePath = serverFilePath; this.localFilePath = localPath; this.requiresUnzip = requiresUnzip; } защищенный DownloadRequest (Parcel in) {requiresUnzip = in. readByte ()! = 0x00; serverFilePath = in.readString (); localFilePath = in.readString (); unzipAtFilePath = in.readString (); deleteZipAfterExtract = in.readByte ()! = 0x00; } @Override public int describeContents () {return 0; } @Override public void writeToParcel (Parcel dest, int flags) {dest.writeByte ((byte) (requiresUnzip? 0x01: 0x00)); dest.writeString (serverFilePath); dest.writeString (localFilePath); dest.writeString (unzipAtFilePath); dest.writeByte ((byte) (deleteZipAfterExtract? 0x01: 0x00)); } @SuppressWarnings ("unused") public static final Parcelable.Creator CREATOR = new Parcelable.Creator () {@Override public DownloadRequest createFromParcel (Parcel in) {return new DownloadRequest (in); } @Override public DownloadRequest [] newArray (int size) {return new DownloadRequest [size]; }}; публичное логическое isRequiresUnzip () {return requiresUnzip; } public void setRequiresUnzip (логическое значение requiresUnzip) {this.requiresUnzip = requiresUnzip; } общедоступная строка getServerFilePath () {return serverFilePath; } public void setServerFilePath (String serverFilePath) {this.serverFilePath = serverFilePath; } общедоступная строка getLocalFilePath () {return localFilePath; } public void setLocalFilePath (String localFilePath) {this.localFilePath = localFilePath; } общедоступный статический создатель getCreator () {return CREATOR; } общедоступная строка getUnzipAtFilePath () {return unzipAtFilePath; } public void setUnzipAtFilePath (String unzipAtFilePath) {this.unzipAtFilePath = unzipAtFilePath; } общедоступная строка getTag () {тег возврата; } public void setTag (String tag) {this.tag = tag; } публичное логическое isDeleteZipAfterExtract () {return deleteZipAfterExtract; } public void setDeleteZipAfterExtract (логическое deleteZipAfterExtract) {this.deleteZipAfterExtract = deleteZipAfterExtract; }} частное статическое логическое значение isOnline (контекст контекста) {ConnectivityManager cm = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo (); if (netInfo! = null && netInfo.isConnectedOrConnecting () && cm.getActiveNetworkInfo (). isAvailable () && cm.getActiveNetworkInfo (). isConnected ()) {return true; } return false; }}
Пример использования:
String serverFilePath = "http://www.colorado.edu/conflict/peace /download/peace_problem.ZIP";String path = FileUtils.getDataDir (context) .getAbsolutePath (); String fileName = "sample_download"; File file = new File (path, fileName); String localPath = file.getAbsolutePath (); String unzipPath = FileUtils.getDataDir (context, «ExtractLoc»). getAbsolutePath (); FileDownloadService.DownloadRequest downloadRequest = new FileDownloadService.DownloadRequest (serverFilePath, localPath); downloadRequest.setRequiresUnzipAleteDownload (true); unzipPath); FileDownloadService. OnDownloadStatusListener listener = new FileDownloadService.OnDownloadStatusListener () {@Override public void onDownloadStarted () {} @Override public void onDownloadCompleted () {} @Override public void onDownloadFailed () {} @Override общедоступный void onDownloadFailed () {} @Override {} FileDownloadService.FileDownloader downloader = FileDownloadService.FileDownloader.getInstance (downloadRequest, listener); downloader.download (context);
Также вы можете использовать (при необходимости) FileUtils.java
import android.content.Context; import java.io.File; public class FileUtils {public static File getDataDir (Context context) {String path = context.getFilesDir (). getAbsolutePath () + "/SampleZip"; Файл файл = новый файл (путь); если (! file.exists ()) {file.mkdirs (); } файл возврата; } общедоступный статический файл getDataDir (контекст контекста, строковая папка) {String path = context.getFilesDir (). getAbsolutePath () + "/" + папка; Файл файл = новый файл (путь); если (! file.exists ()) {file.mkdirs (); } возвратный файл; }}
Я написал IntentService
, который вместе с прогрессом:
Добавьте следующий класс службы в свое приложение (также объявите его в файле манифеста приложения):
import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Parcel; import android.os.Parcelable; import android.os.ResultReceiver; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java .net.URLConnection; импорт java.util.Enumera tion; import java.util.zip.ZipEntry; import java.util.zip.ZipFile;/** * Создано Vaibhav.Jani 4.06.15. */открытый класс FileDownloadService расширяет IntentService {private static int STATUS_OK = 100; частный статический int STATUS_FAILED = 200; частная статическая финальная строка DOWNLOADER_RECEIVER = "downloader_receiver"; частная статическая финальная строка DOWNLOAD_DETAILS = "download_details"; приватная статическая финальная строка DOWNLOAD_STARTED = "download_started"; закрытая статическая конечная строка DOWNLOAD_FAILED = "download_failed"; закрытая статическая конечная строка DOWNLOAD_COMPLETED = "download_completed"; частная статическая финальная строка DOWNLOAD_PROGRESS = "download_progress"; общедоступный FileDownloadService () {супер (""); } @Override protected void onHandleIntent (намерение намерения) {Bundle bundle = intent.getExtras (); if (bundle == null ||! bundle.containsKey (DOWNLOADER_RECEIVER) ||! bundle. containsKey (DOWNLOAD_DETAILS)) {возврат; } ResultReceiver resultReceiver = bundle.getParcelable (DOWNLOADER_RECEIVER); DownloadRequest downloadDetails = bundle.getParcelable (DOWNLOAD_DETAILS); попробуйте {assert downloadDetails! = null; URL url = новый URL (downloadDetails.getServerFilePath ()); URLConnection urlConnection = url.openConnection (); urlConnection.connect (); int lengthOfFile = urlConnection.getContentLength (); Log.d ("FileDownloaderService", "Длина файла:" + lengthOfFile); downloadStarted (resultReceiver); InputStream input = новый BufferedInputStream (url.openStream ()); String localPath = downloadDetails.getLocalFilePath (); OutputStream output = новый FileOutputStream (localPath); байтовые данные [] = новый байт [1024]; длинный итог = 0; int count; while ((count = input.read (data))! = -1) {total + = count; int progress = (int) ((всего * 100)/lengthOfFile); sendProgress (прогресс, resultReceiver); output.write (данные, 0, количество); } output.flush (); output.close (); input.close (); if (downloadDetails.isRequiresUnzip ()) {String unzipDestination = downloadDetails.getUnzipAtFilePath (); if (unzipDestination == null) {файл файл = новый файл (localPath); unzipDestination = file.getParentFile (). getAbsolutePath (); } распаковать (localPath, unzipDestination); } downloadCompleted (resultReceiver); if (downloadDetails.isDeleteZipAfterExtract ()) {Файл файл = новый файл (localPath); file.delete (); }} catch (исключение e) {e.printStackTrace (); downloadFailed (resultReceiver); }} public void sendProgress (int progress, получатель ResultReceiver) {Bundle progressBundle = new Bundle (); progressBundle.putInt (FileDownloadService.DOWNLOAD_PROGRESS, прогресс); Receiver.send (STATUS_OK, progressBundle); } public void downloadStarted (ResultReceiver resultReceiver) {Bundle progressBundle = new Bundle (); progressBundle.putBoolean (FileDownloadService.DOWNLOAD_STARTED, истина); resultReceiver.send (STATUS_OK, progressBundle); } public void downloadCompleted (ResultReceiver resultReceiver) {Bundle progressBundle = new Bundle (); progressBundle.putBoolean (FileDownloadService.DOWNLOAD_COMPLETED, истина); resultReceiver.send (STATUS_OK, progressBundle); } public void downloadFailed (ResultReceiver resultReceiver) {Bundle progressBundle = new Bundle (); progressBundle.putBoolean (FileDownloadService.DOWNLOAD_FAILED, истина); resultReceiver.send (STATUS_FAILED, progressBundle); } private void unzip (String zipFilePath, String unzipAtLocation) выдает исключение {File archive = new File (zipFilePath); попробуйте {ZipFile zipfile = new ZipFile (архив); for (Перечисление e = zipfile.entries (); e.hasMoreElements ();) {ZipEntry entry = (ZipEntry) e.nextElement (); unzipEntry (zipfile, запись, unzipAtLocation); }} catch (Exception e) {Log.e («Распаковать zip», «Разархивировать исключение», e); }} private void unzipEntry (ZipFile zipfile, ZipEntry entry, String outputDir) выдает исключение IOException {if (entry.isDirectory ()) {createDir (новый файл (outputDir, entry.getName ())); вернуть; } Файл outputFile = новый файл (outputDir, запись. getName ()); если (! outputFile.getParentFile (). exists ()) {createDir (outputFile.getParentFile ()); } Log.v ("ZIP E", "Извлечение:" + запись); InputStream zin = zipfile.getInputStream (запись); BufferedInputStream inputStream = новый BufferedInputStream (zin); BufferedOutputStream outputStream = новый BufferedOutputStream (новый FileOutputStream (outputFile)); попробуйте {//IOUtils.copy(inputStream, outputStream); попробуйте {для (int c = inputStream.read (); c! = -1; c = inputStream.read ()) {outputStream.write (c); }} наконец {outputStream.close (); }} наконец {outputStream.close (); inputStream.close (); }} private void createDir (файловый каталог) {if (dir.exists ()) {return; } Log.v ("ZIP E", "Создание каталога" + dir.getName ()); if (! dir.mkdirs ()) {выбросить новое исключение RuntimeException ("Невозможно создать каталог" + каталог); }} открытый статический класс FileDownloader расширяет ResultReceiver {private DownloadRequest downloadDetails; частный OnDownloadStatusListener onDownloadStatusListener; общедоступный статический FileDownloader getInstance (DownloadRequest downloadDetails, OnDownloadStatusListener downloadStatusListener) {Обработчик обработчика = новый обработчик (Looper.getMainLooper ()); FileDownloader fileDownloader = новый FileDownloader (обработчик); fileDownloader.downloadDetails = downloadDetails; fileDownloader.onDownloadStatusListener = downloadStatusListener; return fileDownloader; } публичная недействительная загрузка (контекст контекста) {если (isOnline (контекст)) {намерение намерения = новое намерение (контекст, FileDownloadService.class); intent.putExtra (FileDownloadService.DOWNLOADER_RECEIVER, это); intent.putExtra (FileDownloadService.DOWNLOAD_DETAILS, downloadDetails); context.startService (намерение); }} частный FileDownloader (обработчик обработчика) {super (обработчик); } @Override protected void onReceiveResult (int resultCode, Bundle resultData) {super.onReceiveResult (код результата, результатДанные); если (onDownloadStatusListener == null) {возврат; } if (resultCode == FileDownloadService.STATUS_OK) {if (resultData.containsKey (FileDownloadService.DOWNLOAD_STARTED) && resultData.getBoolean (FileDownloadService.DOWNLOAD_STARTED)) {onDownloadStatusListener. } else if (resultData.containsKey (FileDownloadService.DOWNLOAD_COMPLETED) && resultData.getBoolean (FileDownloadService.DOWNLOAD_COMPLETED)) {onDownloadStatusListener.onDownloadCompleted (); } иначе если (resultData.containsKey (FileDownloadService.DOWNLOAD_PROGRESS)) {int progress = resultData.getInt (FileDownloadService.DOWNLOAD_PROGRESS); onDownloadStatusListener.onDownloadProgress (прогресс); }} иначе, если (resultCode == FileDownloadService.STATUS_FAILED) {onDownloadStatusListener.onDownloadFailed (); }} общедоступный DownloadRequest getDownloadDetails () {return downloadDetails; } public void setDownloadDetails (DownloadRequest downloadDetails) {это. downloadDetails = downloadDetails; } общедоступный OnDownloadStatusListener getOnDownloadStatusListener () {return onDownloadStatusListener; } public void setOnDownloadStatusListener (OnDownloadStatusListener onDownloadStatusListener) {this.onDownloadStatusListener = onDownloadStatusListener; }} общедоступный статический интерфейс OnDownloadStatusListener {void onDownloadStarted (); void onDownloadCompleted (); void onDownloadFailed (); void onDownloadProgress (int progress); } открытый статический класс DownloadRequest реализует Parcelable {private String tag; частное логическое значение requiresUnzip; частная строка serverFilePath; private String localFilePath; частная строка unzipAtFilePath; частное логическое значение deleteZipAfterExtract = true; общедоступный DownloadRequest (String serverFilePath, String localPath) {this.serverFilePath = serverFilePath; this.localFilePath = localPath; this.requiresUnzip = requiresUnzip; } защищенный DownloadRequest (Parcel in) {requiresUnzip = in.readByte ()! = 0x00; serverFilePath = in.readString (); localFilePath = in.readString (); unzipAtFilePath = in.readString (); deleteZipAfterExtract = in.readByte ()! = 0x00; } @Override public int describeContents () {return 0; } @Override public void writeToParcel (Parcel dest, int flags) {dest.writeByte ((byte) (requiresUnzip? 0x01: 0x00)); dest.writeString (serverFilePath); dest.writeString (localFilePath); dest.writeString (unzipAtFilePath); dest.writeByte ((byte) (deleteZipAfterExtract? 0x01: 0x00)); } @SuppressWarnings ("unused") public static final Parcelable.Creator CREATOR = new Parcelable.Creator () {@Override public DownloadRequest createFromParcel (Parcel in) {return new DownloadRequest (in); } @Override public DownloadRequest [] newArray (int size) {return new DownloadRequest [size]; }}; публичное логическое isRequiresUnzip () {return requiresUnzip; } public void setRequiresUnzip (логическое значение requiresUnzip) {this.requiresUnzip = requiresUnzip; } общедоступная строка getServerFilePath () {return serverFilePath; } public void setServerFilePath (String serverFilePath) {this.serverFilePath = serverFilePath; } общедоступная строка getLocalFilePath () {return localFilePath; } public void setLocalFilePath (String localFilePath) {this.localFilePath = localFilePath; } общедоступный статический создатель getCreator () {return CREATOR; } общедоступная строка getUnzipAtFilePath () {return unzipAtFilePath; } public void setUnzipAtFilePath (String unzipAtFilePath) {this.unzipAtFilePath = unzipAtFilePath; } общедоступная строка getTag () {тег возврата; } public void setTag (String tag) {this.tag = tag; } публичное логическое isDeleteZipAfterExtract () {return deleteZipAfterExtract; } public void setDeleteZipAfterExtract (логическое deleteZipAfterExtract) {this.deleteZipAfterExtract = deleteZipAfterExtract; }} частное статическое логическое значение isOnline (контекст контекста) {ConnectivityManager cm = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = см. getActiveNetworkInfo (); if (netInfo! = null && netInfo.isConnectedOrConnecting () && cm.getActiveNetworkInfo (). isAvailable () && cm.getActiveNetworkInfo (). isConnected ()) {return true; } return false; }}
Пример использования:
String serverFilePath = "http://www.colorado.edu/conflict/peace /download/peace_problem.ZIP";String path = FileUtils.getDataDir (context) .getAbsolutePath (); String fileName = "sample_download"; File file = new File (path, fileName); String localPath = file.getAbsolutePath (); String unzipPath = FileUtils.getDataDir (context, «ExtractLoc»). getAbsolutePath (); FileDownloadService.DownloadRequest downloadRequest = new FileDownloadService.DownloadRequest (serverFilePath, localPath); downloadRequest.setRequiresUnzipAleteDownload (true); unzipPath); FileDownloadService.OnDownloadStatusListener listener = new FileDownloadService.OnDownloadStatusListener () {@Override public void onDownloadStarted () {} @Override public void onDownloadCompleted () {} @Override public void onDownloadCompleted () {} @Override public void onDownloadCompleted () () {} @Override public void onDownloadCompleted () () {} @Override public void onDownloadProgram ) {}}; FileDownloadService.FileDownload er downloader = FileDownloadService.FileDownloader.getInstance (downloadRequest, listener); downloader.download (context);
Также вы можете использовать (при необходимости) FileUtils.java
import android.content.Context; import java.io.File; public class FileUtils {public static File getDataDir (Context context) {String path = context.getFilesDir (). getAbsolutePath () + " /SampleZip "; Файл файл = новый файл (путь); если (! file.exists ()) {file.mkdirs (); } возвратный файл; } общедоступный статический файл getDataDir (контекст контекста, строковая папка) {String path = context.getFilesDir (). getAbsolutePath () + "/" + папка; Файл файл = новый файл (путь); если (! file.exists ()) {file.mkdirs (); } возвратный файл; }}
Как сказал JoxTraex: ошибка действительно очевидна.
В строке 129 UnzipManager
вы пытаетесь открыть файл, которого нет. Вот почему вы получаете FileNotFoundException
. Вам следует проверить свой zip-файл, если он правильный и может ли быть правильно извлечен на вашем ПК.
Попробуйте также отладить. Добавьте точку останова в этой строке и позвольте приложению отлаживать и наблюдать, что происходит там, когда появляется конкретное местоположение файла.
Как сказал JoxTraex: ошибка действительно очевидна.
В строке 129 UnzipManager
вы пытаетесь открыть файл, которого нет. Вот почему вы получаете FileNotFoundException
. Вам следует проверить свой zip-файл, если он правильный и может быть правильно извлечен на вашем ПК.
Попробуйте также отладить. Добавьте точку останова в этой строке и позвольте приложению отлаживать и наблюдать, что происходит там, когда появляется конкретное местоположение файла.
Не удаляйте файл, если он существует (потому что файлы будут перезаписаны), или повторно создавайте экземпляр innerFile.
if (innerFile.exists ()) {Log.d ("DEBUG", "Запись уже завершена !, поэтому удаление .."); innerFile.delete ();}//Создать экземпляр заново .innerFile = new File (innerFileName);
При удалении innerFile файл теряется, а при попытке создать каталог с помощью innerFile возникает исключение FileNotFoundException.
Не удаляйте файл, если он существует (потому что файлы будут перезаписаны), или повторно создавайте экземпляр innerFile.
if (innerFile.exists ()) {Log.d ("DEBUG", "Запись уже завершена !, поэтому удаление .."); innerFile.delete ();}//Создаем снова инстанции. /p>
Это последний код, использующий ответ об улучшении производительности, он распаковал файл размером 23 МБ в папку размером 130 МБ ровно за 1 минуту:
открытый класс Decompress {private String _zipFile; private String _location; public Decompress (String zipFile, String location) {_zipFile = zipFile; _location = местоположение; _dirChecker ("");} public void unzip () {попробуйте {FileInputStream fin = new FileInputStream (_zipFile); ZipInputStream zin = новый ZipInputStream (fin); byte b [] = новый байт [1024]; ZipEntry ze = null; while ((ze = zin.getNextEntry ())! = null) {Log.v ("Распаковать", "Распаковать" + ze.getName ()); если (ze.isDirectory ()) {_dirChecker (ze.getName ()); } else {FileOutputStream fout = новый FileOutputStream (_location + ze.getName ()); BufferedInputStream in = новый BufferedInputStream (zin); BufferedOutputStream out = новый BufferedOutputStream (fout); int n; в то время как ((n = in.read (b, 0,1024))> = 0) {out.write (b, 0, n); } zin.closeEntry (); out.close (); }} zin.close (); } catch (Exception e) {Log.e ("Распаковать", "распаковать", e); }} private void _dirChecker (String dir) {Файл f = новый файл (_location + dir); если (! f.isDirectory ()) {f. mkdirs (); }}}
Это последний код, использующий ответ об улучшении производительности, он распакован файл размером 23 МБ в папку 130 МБ ровно за 1 минуту:
открытый класс Decompress {private String _zipFile; private String _location; public Decompress (String zipFile, String location) { _zipFile = zipFile; _location = местоположение; _dirChecker ("");} public void unzip () {попробуйте {FileInputStream fin = new FileInputStream (_zipFile); ZipInputStream zin = новый ZipInputStream (fin); byte b [] = новый байт [1024]; ZipEntry ze = null; while ((ze = zin.getNextEntry ())! = null) {Log.v ("Распаковать", "Распаковать" + ze.getName ()); если (ze.isDirectory ()) {_dirChecker (ze.getName ()); } else {FileOutputStream fout = новый FileOutputStream (_location + ze.getName ()); BufferedInputStream in = новый BufferedInputStream (zin); BufferedOutputStream out = новый BufferedOutputStream (fout); int n; в то время как ((n = in.read (b, 0,1024))> = 0) {out.write (b, 0, n); } zin.closeEntry (); out.close (); }} zin.close (); } catch (Exception e) {Log.e ("Распаковать", "распаковать", e); }} private void _dirChecker (String dir) {Файл f = новый файл (_location + dir); если (! f.isDirectory ()) {f.mkdirs (); }}}