Skip to content

Instantly share code, notes, and snippets.

@Swind
Created September 16, 2011 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Swind/1220935 to your computer and use it in GitHub Desktop.
Save Swind/1220935 to your computer and use it in GitHub Desktop.
[Scala][IO] 下載檔案
package example.http
import java.io._
import java.net.{HttpURLConnection, URL}
/**
* Date: 2011/9/16
* Time: 上午 8:37
*/
class HttpDownloader(urlPath:String,targetPath:String){
val bufferSize = 1024*512
val targetFile = new File(targetPath)
val url = new URL(urlPath)
def download(referer:String="")={
val connect = url.openConnection()
val contentLength = connect.getContentLength
val input = new BufferedInputStream(connect.getInputStream)
val out = new FileOutputStream(targetPath)
val buffer = new Array[Byte](bufferSize)
def readFile(offset:Int=0){
val bytesRead = input.read(buffer,offset,contentLength-offset)
println("bytesRead:"+bytesRead)
if(bytesRead > 0){
out.write(buffer,offset,bytesRead)
out.flush()
readFile(offset+bytesRead)
}
}
readFile()
input.close()
out.close()
}
def upload(referer:String="")={
val connect = url.openConnection().asInstanceOf[HttpURLConnection]
connect.addRequestProperty("Content-Length","59593")
connect.setDoOutput(true)
if(!referer.isEmpty)
connect.addRequestProperty("Referer",referer)
val out = new BufferedOutputStream(connect.getOutputStream)
val input = new BufferedInputStream(new FileInputStream(targetFile))
val buffer = new Array[Byte](bufferSize)
def transfer(offset:Int=0){
val bytesRead = input.read(buffer)
println("bytesRead:"+bytesRead)
if(bytesRead > 0){
out.write(buffer,offset,bytesRead)
out.flush()
transfer(offset+bytesRead)
}
}
transfer()
input.close()
out.close()
}
}
object HttpDownloader{
def main(args: Array[String]) {
// val downloader = new HttpDownloader("http://yblog.org/content/upload/00001_20080315023649.jpg","D:/test.jpg")
// downloader.download()
val uploader = new HttpDownloader("http://reseller.supermicro.com/filefield/ahah/ssm/field_ssm_file/0","D:/test3.jpg")
uploader.upload("http://reseller.supermicro.com/node/add/ssm")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment