0

I seem to need your help again :/

given the following code:

/**
   * 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)

  }

which is in essence downloading a remote file from a url and unzipping it. is there a decent way to write this code in a more elegant non side effecty fashion?

thank you.

Stefan Kunze
  • 741
  • 6
  • 15
  • 2
    I think you meant to write `(help /: given) { question }` instead of `help again :/` – som-snytt Jun 27 '13 at 20:20
  • 1
    IO is inherently side-effecty. But you can still reduce the amount of code you have by library use. Have a look here on how to download: http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java Also consider streaming the downloaded file directly into the BZip2 stream. This should reduce your code to a couple of lines. – gzm0 Jun 27 '13 at 22:46
  • "Also consider streaming the downloaded file directly into the BZip2 stream" howd you do that? can you just create a bzipinputstream with the argument of an inputstream from an url? – Stefan Kunze Jun 28 '13 at 11:43
  • gzm0 you were absolutely right: – Stefan Kunze Jun 28 '13 at 14:30

0 Answers0