내 SD 카드에 zip 폴더가 있는데 어떻게 응용 프로그램 코드 내에서 폴더의 압축을 풉니 다?Android - 폴더의 압축을 풉니 다?
답변
static Handler myHandler;
ProgressDialog myProgress;
public void unzipFile(File zipfile) {
myProgress = ProgressDialog.show(getContext(), "Extract Zip",
"Extracting Files...", true, false);
File zipFile = zipfile;
String directory = null;
directory = zipFile.getParent();
directory = directory + "/";
myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// process incoming messages here
switch (msg.what) {
case 0:
// update progress bar
myProgress.setMessage("" + (String) msg.obj);
break;
case 1:
myProgress.cancel();
Toast toast = Toast.makeText(getContext(),
"Zip extracted successfully",
Toast.LENGTH_SHORT);
toast.show();
provider.refresh();
break;
case 2:
myProgress.cancel();
break;
}
super.handleMessage(msg);
}
};
Thread workthread = new Thread(new UnZip(zipFile, directory));
workthread.start();
}
public class UnZip implements Runnable {
File archive;
String outputDir;
public UnZip(File ziparchive, String directory) {
archive = ziparchive;
outputDir = directory;
}
public void log(String log) {
Log.v("unzip", log);
}
@SuppressWarnings("unchecked")
public void run() {
Message msg;
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries();
e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
msg = new Message();
msg.what = 0;
msg.obj = "Extracting " + entry.getName();
myHandler.sendMessage(msg);
unzipEntry(zipfile, entry, outputDir);
}
} catch (Exception e) {
log("Error while extracting file " + archive);
}
msg = new Message();
msg.what = 1;
myHandler.sendMessage(msg);
}
@SuppressWarnings("unchecked")
public void unzipArchive(File archive, String outputDir) {
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries();
e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, outputDir);
}
} catch (Exception e) {
log("Error while extracting file " + archive);
}
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry,
String outputDir) throws IOException {
if (entry.isDirectory()) {
createDir(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()) {
createDir(outputFile.getParentFile());
}
log("Extracting: " + entry);
BufferedInputStream inputStream = new
BufferedInputStream(zipfile
.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(
new FileOutputStream(outputFile));
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir) {
log("Creating dir " + dir.getName());
if (!dir.mkdirs())
throw new RuntimeException("Can not create dir " + dir);
}
}
이 내가 AsyncTask를 확장하고 주 스레드에서 관찰자를 업데이트 할 수 있습니다 초보자 방법의 수정 된 버전을 사용하고 덕분에 사람들에게 나를 위해
handleMessage()의 case 2는 무엇입니까? 나는 어떤 msg.what = 2를 볼 수 없다. 나를 위해 작동 – Turnsole
하지만, 내가 서버에서 압축 파일을 누른 다음 압축을 풉니 다, 그것은 나를 보여줍니다 java.util.zip.ZipException 오류 : EOCD 찾을 수 없다 그것에 대한 어떤 생각 이건 –
을 일 것입니다. Byte Byte 압축은 매우 느리며 피해야합니다. 대신에 더 효율적인 방법은 많은 양의 데이터를 출력 스트림에 복사하는 것입니다.
private void unzipWebFile(String filename) {
String unzipLocation = getExternalFilesDir(null) + "/unzipped";
String filePath = Environment.getExternalStorageDirectory().toString();
UnZipper unzipper = new UnZipper(filename, filePath, unzipLocation);
unzipper.addObserver(this);
unzipper.unzip();
}
귀하의 관찰자가 update(Observable observable, Object data)
콜백 압축 해제 완료를 얻을 것이다 :
package com.blarg.webviewscroller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Observable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import android.os.AsyncTask;
import android.util.Log;
public class UnZipper extends Observable {
private static final String TAG = "UnZip";
private String mFileName, mFilePath, mDestinationPath;
public UnZipper (String fileName, String filePath, String destinationPath) {
mFileName = fileName;
mFilePath = filePath;
mDestinationPath = destinationPath;
}
public String getFileName() {
return mFileName;
}
public String getFilePath() {
return mFilePath;
}
public String getDestinationPath() {
return mDestinationPath;
}
public void unzip() {
String fullPath = mFilePath + "/" + mFileName + ".zip";
Log.d(TAG, "unzipping " + mFileName + " to " + mDestinationPath);
new UnZipTask().execute(fullPath, mDestinationPath);
}
private class UnZipTask extends AsyncTask<String, Void, Boolean> {
@SuppressWarnings("rawtypes")
@Override
protected Boolean doInBackground(String... params) {
String filePath = params[0];
String destinationPath = params[1];
File archive = new File(filePath);
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, destinationPath);
}
} catch (Exception e) {
Log.e(TAG, "Error while extracting file " + archive, e);
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
setChanged();
notifyObservers();
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry,
String outputDir) throws IOException {
if (entry.isDirectory()) {
createDir(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()) {
createDir(outputFile.getParentFile());
}
Log.v(TAG, "Extracting: " + entry);
BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir) {
if (dir.exists()) {
return;
}
Log.v(TAG, "Creating dir " + dir.getName());
if (!dir.mkdirs()) {
throw new RuntimeException("Can not create dir " + dir);
}
}
}
}
그것은이 같은 Observer
를 구현하는 클래스에 의해 사용됩니다. 때때로 당신이 그것을 압축 해제 후 파일을 삭제하려면 원하는 파일이 있다면 예외를 throw 때문에, 파일을 닫아야합니다 doInBackground()
에서
ZipEtries을 반복 한 후 : 대답 rich.e @에 대한
이것은 받아 들여진 대답이어야합니다. – Prateek
IOUtils를 구할 수있는 곳과 설치 방법은 무엇입니까? –
IOUtils는 Apache Commons IO https://commons.apache.org/proper/commons-io/의 일부입니다. –
은 "부가 기능" 폐쇄되지 않음 :
try {
ZipFile zipfile = new ZipFile(archive);
int entries = zipfile.size();
int total = 0;
if(onZipListener != null)
onZipListener.onUncompressStart(archive);
for (Enumeration<?> e = zipfile.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(onZipListener != null)
onZipListener.onUncompressProgress(archive, (int) (total++ * 100/entries));
unzipEntry(zipfile, entry, path);
}
zipfile.close();
} catch (Exception e) {
e.printStackTrace();
}
- 1. 플렉스로 파일의 압축을 풉니 다?
- 2. 파이썬으로 목록의 압축을 풉니 다?
- 3. .apk에서 파일의 압축을 풉니 다?
- 4. Silverlight에서 프로그래밍 방식으로 다운로드 한 폴더의 압축을 풉니 다.
- 5. Bada os에서 파일의 압축을 풉니 다?
- 6. zip 및 java에서 압축을 풉니 다
- 7. 특정 bzip2 블록의 압축을 풉니 다.
- 8. C에서 4GB 파일의 압축을 풉니 다. #
- 9. 자바를 사용하여 파일 압축을 풉니 다.
- 10. R에서 tar.gz 파일의 압축을 풉니 다.
- 11. 특정 달걀 디렉토리의 압축을 풉니 다.
- 12. Ant 디렉터리에있는 파일의 압축을 풉니 다. Ant
- 13. Wordpress : 첨부 파일의 압축을 풉니 다.
- 14. Gzip과 Bzip은 PHP로 압축을 풉니 다
- 15. 과 같이 압축을 풉니
- 16. Icsharpcode 라이브러리를 사용하여 C# SSIS 스크립트 작업에 압축을 풉니 다.
- 17. BlackBerry Java 응용 프로그램에서 zip 파일의 압축을 풉니 다
- 18. 안드로이드는 프로그래밍 방식으로 RAR 파일 압축을 풉니 다
- 19. 안드로이드에 여러 파일이있는 .zip 파일에서 단일 파일의 압축을 풉니 다.
- 20. iphone sdk에서 압축을 풉니 다 압축 파일의 최대 크기?
- 21. PHP - curl로 압축 파일을 다운로드하고 압축을 풉니 다.
- 22. Mac OS X Leopard에서 Cache.db 파일의 압축을 풉니 다
- 23. rake gems를 실행하는 이유 : Gem :: FilePermissionError의 압축을 풉니 다
- 24. Apache ant로 암호로 보호 된 zip 파일의 압축을 풉니 다?
- 25. 암호로 보호 된 Zip 파일의 압축을 풉니 다.
- 26. I18N 파일 이름으로 WinZIP로 만든 파일의 압축을 풉니 다?
- 27. FTP 클라이언트에서 업로드하기 전에 압축을 풀고 업로드 후 서버에서 압축을 풉니 다.
- 28. Ruby를 사용하여 이진 문자열에서 비트를 풉니 다.
- 29. NSMutableArray의 -removeLastObject가 객체를 풉니 다?
- 30. python ZipFile을 사용하여 구조를 유지하지 않고 zip에서 파일의 압축을 풉니 다?
외부 저장소에 대한 액세스 권한을 추가하셨습니까? – Kurru