這篇文章是關於如何編寫一個實用程序類,用於使用內置的Java API在壓縮的zip歸檔文件中提取文件和目錄。
java.util.zip包提供下列類用於從ZIP文件中提取文件和目錄:
ZipInputStream:這是可被用於讀取壓縮文件,並提取文件和目錄的主類(條目)。下面是這個類的一些重要用法: - 通過其構造函數讀取ZipInputStream(FileInputStream) - 通過方法讀取文件和目錄條目getNextEntry() - 通過讀取方法讀取當前條目的二進制數據(字節) - 通過方法關閉當前條目closeEntry() - 通過close方法關閉zip文件()
ZipEntry:此類表示zip文件中的條目。每個文件或目錄都被表示爲一個ZipEntry對象。其方法getName()返回一個表示文件/目錄路徑的字符串。路徑的格式如下: folder_1/subfolder_1/subfolder_2/.../subfolder_n/file.ext
根據ZipEntry的路徑,我們在提取zip文件時重新創建目錄結構。
下面的類是用於解壓縮下載zip和解壓縮文件並存儲您的願望位置。
public class UnzipUtil
{
private String zipFile;
private String location;
public UnzipUtil(String zipFile, String location)
{
this.zipFile = zipFile;
this.location = location;
dirChecker("");
}
public void unzip()
{
try
{
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null)
{
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory())
{
dirChecker(ze.getName());
}
else
{
FileOutputStream fout = new FileOutputStream(location + ze.getName());
byte[] buffer = new byte[8192];
int len;
while ((len = zin.read(buffer)) != -1)
{
fout.write(buffer, 0, len);
}
fout.close();
zin.closeEntry();
}
}
zin.close();
}
catch(Exception e)
{
Log.e("Decompress", "unzip", e);
}
}
private void dirChecker(String dir)
{
File f = new File(location + dir);
if(!f.isDirectory())
{
f.mkdirs();
}
}
}
MainActivity.Class:
public class MainActivity extends Activity
{
private ProgressDialog mProgressDialog;
String Url="http://hasmukh/hb.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/unzipFolder/";
String StorezipFileLocation =Environment.getExternalStorageDirectory() + "/DownloadedZip";
String DirectoryName=Environment.getExternalStorageDirectory() + "/unzipFolder/files/";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadZipfile mew = new DownloadZipfile();
mew.execute(url);
}
//-This is method is used for Download Zip file from server and store in Desire location.
class DownloadZipfile extends AsyncTask<String, String, String>
{
String result ="";
@Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
@Override
protected String doInBackground(String... aurl)
{
int count;
try
{
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(StorezipFileLocation);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.close();
input.close();
result = "true";
} catch (Exception e) {
result = "false";
}
return null;
}
protected void onProgressUpdate(String... progress)
{
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused)
{
mProgressDialog.dismiss();
if(result.equalsIgnoreCase("true"))
{
try
{
unzip();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
}
}
}
//This is the method for unzip file which is store your location. And unzip folder will store as per your desire location.
public void unzip() throws IOException
{
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Please Wait...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
new UnZipTask().execute(StorezipFileLocation, DirectoryName);
}
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);
}
UnzipUtil d = new UnzipUtil(StorezipFileLocation, DirectoryName);
d.unzip();
}
catch (Exception e)
{
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean result)
{
mProgressDialog.dismiss();
}
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("", "Extracting: " + entry);
BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
try
{
}
finally
{
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir)
{
if (dir.exists())
{
return;
}
if (!dir.mkdirs())
{
throw new RuntimeException("Can not create dir " + dir);
}
}}
}
Note: Do not forgot to add below permission in android Manifest.xml file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
Read More
非常感謝兄弟..這就是我正在尋找.. – 2013-11-12 14:45:23
@RathaKrishna IM面臨着落後的問題斜線我得到的文件路徑像SD卡/溫度/ 765 \ 765.json有什麼辦法來解決 – 2014-12-17 02:57:11
@Ando filepath = filepath.replace(「\」,「/」); – 2017-04-25 23:19:47