下载和解压缩 - 简化客户端代码

时间:2013-06-27 18:38:12

标签: scala bzip2

我似乎再次需要你的帮助:/

给出以下代码:

/**
   * downloads a url (file) to a desired file name
   */
  def downloadFile(url: URL, filename: String) {
    commonOp(url2InputStream(url), filename)
  }

  /**
   * common method for writing data from an inputstream to an outputstream
   */
  def commonOp(is: InputStream, filename: String) {
    val out: OutputStream = file2OutputStream(filename)
    try {
      deleteFileIfExists(filename)
      copy(is, out)
    } catch {
      case e: Exception => println(e.printStackTrace())
    }

    out.close()
    is.close()

  }

  /**
   * copies an inputstream to an  outputstream
   */
  def copy(in: InputStream, out: OutputStream) {
    val buffer: Array[Byte] = new Array[Byte](1024)
    var sum: Int = 0
    Iterator.continually(in.read(buffer)).takeWhile(_ != -1).foreach({ n => out.write(buffer, 0, n); (sum += buffer.length); println(sum + " written to output "); })
  }

  /**
   * handling of bzip archive files
   */
  def unzipFile(fn: String, outputFileName: String) {
    val in = new BZip2CompressorInputStream(new FileInputStream(fn))
    commonOp(in, outputFileName)

  }

本质上是从URL下载远程文件并解压缩它。 是否有一种不错的方式以更优雅的非副作用方式编写此代码?

谢谢。

0 个答案:

没有答案