`

java 解压缩文件

    博客分类:
  • java
阅读更多
/**
* http远程请求,获取csv数据
* httpCsvZipPath:原网站zip路径
* localZipPath:下载到本地zip路径
* localUnZipPath:解压后unzip路径
*/
public static boolean httpInvokeGetFile(String httpCsvZipPath,String localZipPath){
File zipOutFile = null;
//zip文件输出路径
zipOutFile = getFilePath(localZipPath);
//http 获取远程url 内容
try {
URL url = new URL(httpCsvZipPath);
InputStream ins = url.openConnection().getInputStream();
FileOutputStream fos = new FileOutputStream(zipOutFile,false);
byte[] b = new byte[1024];
int c;
if (ins != null) {
//删除文件(不用删除,直接覆盖)
//deleteTempIndexPathFile(rootPath);
//
ins.available(); //非常重要,本地可以不需要,linux上必须。

while((c=ins.read(b)) != -1){
fos.write(b,0,c);
}
} else {
logger.info("no content"+url);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return false;
}
return true;

}
/**
* zip解压包括一个文件

* @param zipFilePath 被解压zip文件路径
* @param unzipFilePath  解压后文件路径

*/
public static boolean unZipOneFile(String zipFilePath,String unzipFilePath) {
OutputStream out = null;
ZipInputStream in = null;
try {
File zipFile = getFilePath(zipFilePath);
File unzipFile = getFilePath(unzipFilePath);

in = new ZipInputStream(new FileInputStream(zipFile));
out = new FileOutputStream(unzipFile);
ZipEntry dataLine = in.getNextEntry();
byte[] buf = new byte[1024];
if(dataLine != null){//可以适当加个判断,行是否取完为空.
int i = 0;
while ((i = in.read(buf)) > 0){
out.write(buf, 0, i);
}
}
} catch (Exception e) {
logger.info("java zip err==>"+e.getMessage());
e.printStackTrace();
return false;
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
// TODO: handle exception
}
}
return true;
}
/**
   * 解压缩(包括多个文件)

   * @param zipfile File 需要解压缩的文件

   * @param descDir String 解压后的目标目录
   */
@SuppressWarnings("unchecked")
public static void unZipMoreFiles(String zipfilePath, String descDir) {
  try {
    File fileDir = new File(descDir);
    if (!fileDir.exists()) {
    fileDir.mkdirs();
}
            ZipFile zf=new ZipFile(zipfilePath);
            for(Enumeration entries=zf.entries();entries.hasMoreElements();){
                ZipEntry entry=(ZipEntry) entries.nextElement();
                String zipEntryName=entry.getName();
                InputStream in=zf.getInputStream(entry);

File file = new File(descDir+zipEntryName);
if (entry.isDirectory()) {
if (!file.exists()) {
file.mkdirs();
}
continue;
} else {
file.createNewFile();
}
                OutputStream out=new FileOutputStream(file);
                byte[] buf1=new byte[1024];
                int len;
                while((len=in.read(buf1))>0){
                    out.write(buf1,0,len);
                }
                in.close();
                out.close();
                System.out.println("解压缩完成.");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics