1. 程式人生 > >Java的http獲取檔案

Java的http獲取檔案

設定範圍和和使用RandomAccessFile :

    private void download() throws IOException {
	HttpURLConnection httpConn = null;
	    
	httpConn = (HttpURLConnection) url.openConnection();
	httpConn.setRequestMethod("POST");
	httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14");
	
	InputStream in = httpConn.getInputStream();
	oSavedFile.seek(beginIndex);
	byte[] b = new byte[1024];
	int nRead;
	while((nRead = in.read(b,0,1024)) != -1 )
	{
		oSavedFile.write(b,0,nRead);
		System.out.println(nRead);
		System.out.println(Thread.currentThread().getName());
	}
    }
多執行緒的下載
             int length = httpConn.getContentLength();
	    RandomAccessFile oSavedFile =  new RandomAccessFile("down.html","rw");
	   // oSavedFile.setLength(length);
	    // 執行緒個數5
	    int threadNum = 2;
	    int singleLength = length / threadNum;
	    
	    for(int i=0; i