我似乎再次需要你的帮助:/
给出以下代码:
/**
* 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 下载远程文件并解压缩。有没有一种体面的方法可以以更优雅的无副作用方式编写此代码?
谢谢你。