Android的解压android系统编程文件 [英] Android Unzipping files Programmatically in android

查看:205
本文介绍了Android的解压android系统编程文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下载一个压缩文件夹,并保存在我的Andr​​oid应用程序device.My特定的文件夹没有访问该文件夹,因为它被压缩。我想从服务器下载后解压缩的文件夹,并保存在特定的文件夹。我的code是在这里不用

 公共无效DownloadDatabase(字符串DownloadUrl,字符串文件名){
    尝试 {
        文件根= android.os.Environment.getExternalStorageDirectory();
        文件DIR =新的文件(root.getAbsolutePath()+/ timy /数据库);
        如果(dir.exists()== FALSE){
             dir.mkdirs();
        }

        网址URL =新的URL(http://myexample.com/android/timy.zip);
        档案文件=新的文件(目录,文件名);

        长的startTime = System.currentTimeMillis的();
        Log.d(下载管理器,下载网址:+网址);
        Log.d(下载管理器,下载文件的名称:+文件名);

        URLConnection的康涅狄格大学= url.openConnection();
        uconn.setConnectTimeout(TIMEOUT_SOCKET);

        InputStream的是= uconn.getInputStream();

        ZipInputStream zipinstream =新ZipInputStream(新的BufferedInputStream(是));
        的ZipEntry ZipEntry的;

        而((ZipEntry的= zipinstream.getNextEntry())!= NULL){
            串zipE​​ntryName = zipEntry.getName();
            档案文件1 =新的文件(文件+ zipEntryName);
            如果(file1.exists()){

            }其他{
                如果(zipEntry.isDirectory()){
                    file1.mkdirs();
                }
            }
        }

        的BufferedInputStream bufferinstream =新的BufferedInputStream(是);

        ByteArrayBuffer BAF =新ByteArrayBuffer(5000);
        INT电流= 0;
        而((电流= bufferinstream.read())!=  -  1){
            baf.append((字节)电流);
        }

        FileOutputStream中FOS =新的FileOutputStream(文件);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        Log.d(下载管理器,下载现成的+((System.currentTimeMillis的() -  startTime时)/ 1000)+SEC);
    }
    赶上(IOException异常E){
        Log.d(下载管理,错误:+ E);
        e.printStackTrace();
    }

}
 

和我的logcat是否显示在错误。只是文件夹中创建我的设备,没有文件下载与解压...    对于使用inputZipStream出来的方法,然后我的压缩文件夹中下载并保存在SD卡。当我想将它解压缩,是不会发生。

谁能帮我解决这个问题。

在此先感谢。

解决方案

这篇文章是关于如何写一个工具类提取的com pressed zip压缩包的文件和目录,使用内置的Java API。

java.util.zip包提供下列类从一个ZIP压缩文件解压缩文件和目录:

ZipInputStream:这是一种可用于存档中读取并解压文件和目录(项)的主类。下面是这个类的一些重要的用途: 通过其构造函数ZipInputStream -read一个zip(的FileInputStream) 经由方法getNextEntry文件和目录)-read条目( 通过方法当前条目的读取-read二进制数据(字节) 通过方法closeEntry -close当前条目() 通过方法接近-close zip文件()

的ZipEntry:这个类重presents在zip文件中的条目。每个文件或目录是psented作为的ZipEntry对象重新$ P $。它的getName()方法返回一个字符串,它再次文件/目录presents路径。该路径是以下形式: folder_1 / subfolder_1 / subfolder_2 / ... / subfolder_n / file.ext

基于的ZipEntry的道路

,我们重新创建解压压缩文件时的目录结构。

下面类用于解压下载的zip和提取文件和存储你的愿望的位置。

 公共类UnzipUtil
  {
     私人字符串的压缩文件;
     私人字符串的位置;

  公共UnzipUtil(字符串的压缩文件,字符串位置)
  {
     this.zipFile = zip文件;
     this.location =位置;

     dirChecker();
  }

  公共无效解压缩()
 {
   尝试
 {
      的FileInputStream鳍=新的FileInputStream(zip文件);
      ZipInputStream ZIN =新ZipInputStream(翅);
      ZipEntry的泽= NULL;
      而((泽= zin.getNextEntry())!= NULL)
      {
       Log.v(DECOM preSS的,解压缩+ ze.getName());

如果(ze.isDirectory())
{
 dirChecker(ze.getName());
}
其他
{
 FileOutputStream中FOUT =新的FileOutputStream(位置+ ze.getName());

 byte []的缓冲区=新的字节[8192];
 INT LEN;
 而((LEN = zin.read(缓冲液))!=  -  1)
 {
  fout.write(缓冲液,0,LEN);
 }
 fout.close();

 zin.closeEntry();

}

    }
      zin.close();
    }
     赶上(例外五)
     {
          Log.e(DECOM preSS,解压,E);
     }

  }

   私人无效dirChecker(字符串DIR)
   {
         文件F =新的文件(位置+方向);
         如果(!f.isDirectory())
          {
            f.mkdirs();
          }
         }
    }
 

  

MainActivity.Class:

 公共类MainActivity扩展活动
        {
        私人ProgressDialog mProgressDialog;

        字符串URL =HTTP://hasmukh/hb.zip;
        串unzipLocation = Environment.getExternalStorageDirectory()+/ unzipFolder /;
        字符串StorezipFileLocation = Environment.getExternalStorageDirectory()+/ DownloadedZip;
       字符串目录名= Environment.getExternalStorageDirectory()+/ unzipFolder /文件/;

       @覆盖
       保护无效的onCreate(包savedInstanceState)
       {
         super.onCreate(savedInstanceState);
         的setContentView(R.layout.main);

           DownloadZipfile MEW =新DownloadZipfile();
            mew.execute(URL);

        }

        //  - 这是方法用于从服务器和存储欲望位置下载Zip文件。
        类DownloadZipfile扩展的AsyncTask<字符串,字符串,字符串>
         {
         字符串结果=;
          @覆盖
          在preExecute保护无效()
          {
            super.on preExecute();
            mProgressDialog =新ProgressDialog(MainActivity.this);
            mProgressDialog.setMessage(下载...);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(假);
            mProgressDialog.show();
            }

             @覆盖
             保护字符串doInBackground(字符串... aurl)
             {
              诠释计数;

                    尝试
          {
网址URL =新的URL(aurl [0]);
URLConnection的体conexion = url.openConnection();
conexion.connect();
INT lenghtOfFile = conexion.getContentLength();
的InputStream输入=新的BufferedInputStream(url.openStream());

的OutputStream输出=新的FileOutputStream(StorezipFileLocation);

字节的数据[] =新的字节[1024];
总长= 0;

而((计数= input.read(数据))!=  -  1)
{
 共有+ =计数;
 publishProgress(+(int)的((总* 100)/ lenghtOfFile));
 output.write(数据,0,计数);
}
output.close();
input.close();
结果=真;

         }赶上(例外五){

         结果=假;
         }
        返回null;

       }
        保护无效onProgressUpdate(字符串...进度)
        {
        Log.d(ANDRO_ASYNC,进步[0]);
        mProgressDialog.setProgress(的Integer.parseInt(进展[0]));
        }

         @覆盖
         保护无效onPostExecute(字符串使用)
         {
               mProgressDialog.dismiss();
               如果(result.equalsIgnoreCase(真))
         {
          尝试
             {
                解压缩();
                   }赶上(IOException异常E)
                   {
                 // TODO自动生成的catch块
              e.printStackTrace();
              }
                 }
                     其他
                   {

                   }
                       }
               }
          //这是方法解压缩文件,该文件是存储您的位置。并解压缩文件夹将存放按照你的愿望的位置。



             公共无效解压缩()抛出IOException异常
            {
            mProgressDialog =新ProgressDialog(MainActivity.this);
            mProgressDialog.setMessage(请稍候...);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(假);
            mProgressDialog.show();
            新UnZipTask()执行(StorezipFileLocation,目录名);
              }


          私有类UnZipTask扩展的AsyncTask<字符串,太虚,布尔>
          {
          @燮pressWarnings(rawtypes)
          @覆盖
          保护布尔doInBackground(字符串... PARAMS)
          {
             串文件路径= PARAMS [0];
             串的DestinationPath = PARAMS [1];

               文件归档=新的文件(文件路径);
                尝试
                 {
                 ZipFile的zip文件=新的ZipFile(存档);
                 对于(枚举E = zipfile.entries(); e.hasMoreElements();)
                 {
                         ZipEntry的入口=(ZipEntry的)e.nextElement();
                         unzipEntry(zip文件,录入,的DestinationPath);
                    }


         UnzipUtil D =新UnzipUtil(StorezipFileLocation,目录名);
         d.unzip();

            }
    赶上(例外五)
         {
           返回false;
         }

          返回true;
       }

           @覆盖
           保护无效onPostExecute(布尔结果)
           {
                mProgressDialog.dismiss();

             }


            私人无效unzipEntry(ZipFile中的压缩文件,ZipEntry的入口,字符串outputDir)抛出IOException异常
         {

                  如果(entry.isDirectory())
        {
                createDir(新文件(outputDir,entry.getName()));
                返回;
          }

           文件OUTPUTFILE =新的文件(outputDir,entry.getName());
           如果(!outputFile.getParentFile()。存在())
           {
              createDir(outputFile.getParentFile());
           }

           // Log.v(,提取+条目);
          的BufferedInputStream的InputStream =新的BufferedInputStream(zipfile.getInputStream(项));
          的BufferedOutputStream的OutputStream =新的BufferedOutputStream(新的FileOutputStream(OUTPUTFILE));

       尝试
        {

         }
       最后
         {
              outputStream.flush();
              outputStream.close();
              inputStream.close();
          }
           }

             私人无效createDir(文件目录)
             {
                如果(dir.exists())
              {
                   返回;
                  }
                    如果(!dir.mkdirs())
                      {
                        抛出新的RuntimeException(无法创建目录+方向);
               }
               }}
                 }

            注意:不要忘了添加以下许可Android的Manifest.xml文件。

          <使用-权限的Andr​​oid:名称=android.permission.WRITE_EXTERNAL_STORAG​​E>< /使用-许可>
      <使用-权限的Andr​​oid:名称=android.permission.INTERNET对/>
 

更多

I am downloading a zip folder and saving in specific folder in my android device.My application is not accessing the folder as it is zipped. I would like to unzip the folder after downloading from server and save in specific folder. and my code is here goes

public void DownloadDatabase(String DownloadUrl, String fileName) {
    try {
        File root = android.os.Environment.getExternalStorageDirectory();
        File dir = new File(root.getAbsolutePath() + "/timy/databases");
        if(dir.exists() == false){
             dir.mkdirs();  
        }

        URL url = new URL("http://myexample.com/android/timy.zip");
        File file = new File(dir,fileName);

        long startTime = System.currentTimeMillis();
        Log.d("DownloadManager" , "download url:" +url);
        Log.d("DownloadManager" , "download file name:" + fileName);

        URLConnection uconn = url.openConnection();
        uconn.setConnectTimeout(TIMEOUT_SOCKET);

        InputStream is = uconn.getInputStream();

        ZipInputStream zipinstream = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry zipEntry;

        while((zipEntry = zipinstream.getNextEntry()) != null){
            String zipEntryName = zipEntry.getName();
            File file1 = new File(file + zipEntryName);
            if(file1.exists()){

            }else{
                if(zipEntry.isDirectory()){
                    file1.mkdirs();
                }
            }
        }

        BufferedInputStream bufferinstream = new BufferedInputStream(is);

        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while((current = bufferinstream.read()) != -1){
            baf.append((byte) current);
        }

        FileOutputStream fos = new FileOutputStream( file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
    }
    catch(IOException e) {
        Log.d("DownloadManager" , "Error:" + e);
        e.printStackTrace();
    }

}

and my logcat is showing on error. just folder is creating in my device and no files are downloading with unzipped... With out using inputZipStream method then My zipped folder is downloading and saving in sdcard. when I want to unzip it, is not happening..

can anyone help me to overcome the issue..

Thanks in advance.

解决方案

This article is about how to write a utility class for extracting files and directories in a compressed zip archive, using built-in Java API.

The java.util.zip package provides the following classes for extracting files and directories from a ZIP archive:

ZipInputStream: this is the main class which can be used for reading zip file and extracting files and directories (entries) within the archive. Here are some important usages of this class: -read a zip via its constructor ZipInputStream(FileInputStream) -read entries of files and directories via method getNextEntry() -read binary data of current entry via method read(byte) -close current entry via method closeEntry() -close the zip file via method close()

ZipEntry: this class represents an entry in the zip file. Each file or directory is represented as a ZipEntry object. Its method getName() returns a String which represents path of the file/directory. The path is in the following form: folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext

Based on the path of a ZipEntry, we re-create directory structure when extracting the zip file.

Below class is used for unzip download zip and extract file and store your desire location.

  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

这篇关于Android的解压android系统编程文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆