如何使用scala解压zip文件? [英] How to unzip a zip file using scala?

查看:202
本文介绍了如何使用scala解压zip文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要解压缩.zip文件,该文件包含一个名为modeled的文件夹,后者又包含一些excel文件。



我有一些运气找到已经写的代码(ZipArchive),这意味着要解压缩zip文件,但是我无法弄清楚为什么它会抛出一个错误消息当我使用它ZipArchive的代码和错误消息如下所示:

  import java.io. {OutputStream,InputStream,File,FileOutputStream} 
import java.util.zip。{ZipEntry,ZipFile}
import scala.collection.JavaConversions._

object ZipArchive {

val BUFSIZE = 4096
val buffer = new Array [Byte](BUFSIZE)

def unZip(source:String,targetFolder:String)= {
val zipFile = new ZipFile(source)

unzipAllFile(zipFile.entries.toList,getZipEntryInputStream(zipFile)_,新文件(targetFolder))
}

def getZipEntryInputStream(zipFile:ZipFile)(条目: ZipEntry)= zipFile.getInputStream(entry)

def unzipAllFile(entryList:List [ZipEntry],inputGetter:(ZipEntry)=> InputStream,targetFolder:File):Boolean = {

entryList match {
case entry :: entries =>

如果(entry.isDirectory)
new File(targetFolder,entry.getName).mkdirs
else
saveFile(inputGetter(entry),new FileOutputStream (targetFolder,entry.getName)))

unzipAllFile(entries,inputGetter,targetFolder)
case _ =>
true
}
}

def saveFile(fis:InputStream,fos:OutputStream)= {
writeToFile(bufferReader(fis)_,fos)
fis.close
fos.close
}

def bufferReader(fis:InputStream)(buffer:Array [Byte])=(fis.read(buffer) ,缓冲区)

def writeToFile(reader:(Array [Byte])=> Tuple2 [Int,Array [Byte]],fos:OutputStream):Boolean = {
val ,数据)= reader(buffer)
if(length> = 0){
fos.write(data,0,length)
writeToFile(reader,fos)
} else
true
}
}

错误消息: p>

  java.io.FileNotFoundException:src / test / resources / oepTemp / modeled / EQ_US_2_NULL _('CA')_ ALL_ELT_IL_EQ_US.xlsx文件或目录),在java.io.FileOutputStream.open(本机方法)
[error]在java.io.FileOutputStream。(init)(FileOutputStream.java: 221)
[err或[]在java.io.FileOutputStream。< init>(FileOutputStream.java:171)
[error] at com.contract.testing.ZipArchive $ .unzipAllFile(ZipArchive.scala:28)
[错误]在com.contract.testing.ZipArchive $ .unZip(ZipArchive.scala:15)
[error] at com.contract.testing.OepStepDefinitions $$ anonfun $ 1.apply $ mcZ $ sp(OepStepDefinitions.scala: 175)
[error] at com.contract.testing.OepStepDefinitions $$ anonfun $ 1.apply(OepStepDefinitions.scala:150)
[error] at com.contract.testing.OepStepDefinitions $$ anonfun $ 1。 (OepStepDefinitions.scala:150)
[error] at cucumber.api.scala.ScalaDsl $ StepBody $$ anonfun $ apply $ 1.applyOrElse(ScalaDsl.scala:61)
[error]在黄瓜。 api.scala.ScalaDsl $ StepBody $$ anonfun $ apply $ 1.applyOrElse(ScalaDsl.scala:61)
[error] at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36)
[error ] at cucumber.runtime.scala.ScalaStepDefinition.execute(ScalaStepDefinition.scala:71)
[error] at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
在cucumber.runtime.Runtime.runStep(Runtime.java:298)
[error]在cucumber.runtime.model。 StepContainer.runStep(StepContainer.java:44)
在cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
[error]在cucumber.runtime.model.CucumberScenario中的[错误]。 run(CucumberScenario.java:48)
[error] at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:91)
[error] at cucumber.runtime.junit.FeatureRunner.runChild( FeatureRunner.java:63)
[error] at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
[error] ...

所以基于错误消息,它看起来像是试图找到导出的excel文件?这部分完全抛弃了我。任何帮助将不胜感激。
我下面添加了如何调用该方法,也许我正在做一些愚蠢的事情。另外,如果可以推荐一下,我也可以使用不同的方法来提取我的zip文件。

  val tempDirectoryDir =src / test / resources / oepTemp /
ZipArchive.unZip(tempDirectoryDir +Sub Region Input - Output.zip,tempDirectoryDir)

$ b因为在使用Java的一些实用程序,所以这里是一个这个,翻译成scala,也许这应该更有功能,但它是有用的

 包zip 

import java.io. {IOException,FileOutputStream,FileInputStream,File}
import java .util.zip。{ZipEntry,ZipInputStream}

/ **
*由04/06/15由anquegi创建。
* /
对象Unzip extends App {

val INPUT_ZIP_FILE:String =src / main / resources / my-zip.zip;
val OUTPUT_FOLDER:String =src / main / resources / my-zip;

def unZipIt(zipFile:String,outputFolder:String):Unit = {

val buffer = new Array [Byte](1024)

尝试{

//输出目录
val folder = new File(OUTPUT_FOLDER);
if(!folder.exists()){
folder.mkdir();
}

// zip文件内容
val zis:ZipInputStream = new ZipInputStream(new FileInputStream(zipFile));
//获取压缩文件列表条目
var ze:ZipEntry = zis.getNextEntry();

while(ze!= null){

val fileName = ze.getName();
val newFile = new File(outputFolder + File.separator + fileName);

System.out.println(file unzip:+ newFile.getAbsoluteFile());

//创建文件夹
new File(newFile.getParent())。mkdirs();

val fos = new FileOutputStream(newFile);

var len:Int = zis.read(buffer);

while(len> 0){

fos.write(buffer,0,len)
len = zis.read(buffer)
}

fos.close()
ze = zis.getNextEntry()
}

zis.closeEntry()
zis.close ()

} catch {
case e:IOException => println(exception cat:+ e.getMessage)
}

}

Unzip.unZipIt(INPUT_ZIP_FILE,OUTPUT_FOLDER)



Basically I need to unzip a .zip file which contains a folder called modeled which in turn contains a number of excel files.

I have had some luck in finding code that was already written (ZipArchive) which is meant to unzip the zip file, but I cannot figure out why it throws an error message when I use it. The code for ZipArchive and the error message are listed below:

import java.io.{OutputStream, InputStream, File, FileOutputStream}
import java.util.zip.{ZipEntry, ZipFile}
import scala.collection.JavaConversions._

object ZipArchive {

  val BUFSIZE = 4096
  val buffer = new Array[Byte](BUFSIZE)

  def unZip(source: String, targetFolder: String) = {
    val zipFile = new ZipFile(source)

    unzipAllFile(zipFile.entries.toList, getZipEntryInputStream(zipFile)_, new File(targetFolder))
  }

  def getZipEntryInputStream(zipFile: ZipFile)(entry: ZipEntry) = zipFile.getInputStream(entry)

  def unzipAllFile(entryList: List[ZipEntry], inputGetter: (ZipEntry) => InputStream, targetFolder: File): Boolean = {

    entryList match {
      case entry :: entries =>

        if (entry.isDirectory)
          new File(targetFolder, entry.getName).mkdirs
        else
          saveFile(inputGetter(entry), new FileOutputStream(new File(targetFolder, entry.getName)))

        unzipAllFile(entries, inputGetter, targetFolder)
      case _ =>
        true
    }
  }

  def saveFile(fis: InputStream, fos: OutputStream) = {
    writeToFile(bufferReader(fis)_, fos)
    fis.close
    fos.close
  }

  def bufferReader(fis: InputStream)(buffer: Array[Byte]) = (fis.read(buffer), buffer)

  def writeToFile(reader: (Array[Byte]) => Tuple2[Int, Array[Byte]], fos: OutputStream): Boolean = {
    val (length, data) = reader(buffer)
    if (length >= 0) {
      fos.write(data, 0, length)
      writeToFile(reader, fos)
    } else
      true
  }
}

Error Message:

java.io.FileNotFoundException: src/test/resources/oepTemp/modeled/EQ_US_2_NULL_('CA')_ALL_ELT_IL_EQ_US.xlsx (No such file or directory), took 6.406 sec
[error]     at java.io.FileOutputStream.open(Native Method)
[error]     at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
[error]     at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
[error]     at com.contract.testing.ZipArchive$.unzipAllFile(ZipArchive.scala:28)
[error]     at com.contract.testing.ZipArchive$.unZip(ZipArchive.scala:15)
[error]     at com.contract.testing.OepStepDefinitions$$anonfun$1.apply$mcZ$sp(OepStepDefinitions.scala:175)
[error]     at com.contract.testing.OepStepDefinitions$$anonfun$1.apply(OepStepDefinitions.scala:150)
[error]     at com.contract.testing.OepStepDefinitions$$anonfun$1.apply(OepStepDefinitions.scala:150)
[error]     at cucumber.api.scala.ScalaDsl$StepBody$$anonfun$apply$1.applyOrElse(ScalaDsl.scala:61)
[error]     at cucumber.api.scala.ScalaDsl$StepBody$$anonfun$apply$1.applyOrElse(ScalaDsl.scala:61)
[error]     at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36)
[error]     at cucumber.runtime.scala.ScalaStepDefinition.execute(ScalaStepDefinition.scala:71)
[error]     at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
[error]     at cucumber.runtime.Runtime.runStep(Runtime.java:298)
[error]     at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
[error]     at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
[error]     at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:48)
[error]     at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:91)
[error]     at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
[error]     at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
[error]     ...

So based on the error message it looks like it's trying to find the exported excel file? This part completely throws me off. Any help would be greatly appreciated. I've added below how I'm calling the method, perhaps I'm doing something silly. Also I'm up for using a different way to extract my zip file if you can recommend one.

val tempDirectoryDir = "src/test/resources/oepTemp/"
ZipArchive.unZip(tempDirectoryDir + "Sub Region Input - Output.zip", tempDirectoryDir)

解决方案

Well since were are using some utilities from java, here is a version basen on this, translated to scala, maybe this should be more functional, but it is useful

package zip

import java.io.{ IOException, FileOutputStream, FileInputStream, File }
import java.util.zip.{ ZipEntry, ZipInputStream }

/**
 * Created by anquegi on 04/06/15.
 */
object Unzip extends App {

  val INPUT_ZIP_FILE: String = "src/main/resources/my-zip.zip";
  val OUTPUT_FOLDER: String = "src/main/resources/my-zip";

  def unZipIt(zipFile: String, outputFolder: String): Unit = {

    val buffer = new Array[Byte](1024)

    try {

      //output directory
      val folder = new File(OUTPUT_FOLDER);
      if (!folder.exists()) {
        folder.mkdir();
      }

      //zip file content
      val zis: ZipInputStream = new ZipInputStream(new FileInputStream(zipFile));
      //get the zipped file list entry
      var ze: ZipEntry = zis.getNextEntry();

      while (ze != null) {

        val fileName = ze.getName();
        val newFile = new File(outputFolder + File.separator + fileName);

        System.out.println("file unzip : " + newFile.getAbsoluteFile());

        //create folders
        new File(newFile.getParent()).mkdirs();

        val fos = new FileOutputStream(newFile);

        var len: Int = zis.read(buffer);

        while (len > 0) {

          fos.write(buffer, 0, len)
          len = zis.read(buffer)
        }

        fos.close()
        ze = zis.getNextEntry()
      }

      zis.closeEntry()
      zis.close()

    } catch {
      case e: IOException => println("exception caught: " + e.getMessage)
    }

  }

  Unzip.unZipIt(INPUT_ZIP_FILE, OUTPUT_FOLDER)

}

这篇关于如何使用scala解压zip文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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