java實現斷點續傳
用java的URL實現了一個簡單的斷點續傳的列子,不為別的,假如你對斷點續傳不了解一看就明白了呵呵,算不上高深啊
package test;import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection;
/* @className:TestDown.java
- @classDescription: 簡單的java斷點續傳
- @author:jiangmianyue
- @createTime:2011-11-29
*/
public class TestDown {
public static void main(String[] args) {
} // 下面是一些請求頭信息可以根據需要添加 private static void setHeader(URLConnection con) {URL url = null; try { url = new URL("http://172.16.1.33/newfile/e358beb5367341929614332e1a390dfb.apk"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection httpConnection = null; try { // 建立連接 httpConnection = url.openConnection(); } catch (IOException e) { e.printStackTrace(); } // 設置ua httpConnection.setRequestProperty("User-Agent","NetFox"); // 設置斷點續傳的開始位置 從100k開始 httpConnection.setRequestProperty("RANGE","bytes=102400-"); // 獲得輸入流 InputStream input = null; try { input = httpConnection.getInputStream(); } catch (IOException e) { e.printStackTrace(); } // 可以從多少字節開始寫的文件類 RandomAccessFile oSavedFile = null; try { oSavedFile = new RandomAccessFile("d://down.apk","rw"); } catch (FileNotFoundException e) { e.printStackTrace(); } // 從第100K開始寫 long nPos = 102400; // 定位文件指針到 nPos 位置 try { // 文件指針移動到那個位置 oSavedFile.seek(nPos); } catch (IOException e) { e.printStackTrace(); } byte[] b = new byte[1024]; int nRead; // 從輸入流中讀入字節流,然后寫到文件中 try { // int n =0; while((nRead=input.read(b,0,1024)) > 0) { oSavedFile.write(b,0,nRead); /** * 第一次的時設置n的值到100的時候斷開 * if(100 == n){ * break; * } */ } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
} }</pre>轉自: http://xuehanxin.iteye.com/blog/1284272con.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.3) Gecko/2008092510 Ubuntu/8.04 (hardy) Firefox/3.0.3"); con.setRequestProperty("Accept-Language", "en-us,en;q=0.7,zh-cn;q=0.3"); con.setRequestProperty("Accept-Encoding", "aa"); con.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); con.setRequestProperty("Keep-Alive", "300"); con.setRequestProperty("Connection", "keep-alive"); con.setRequestProperty("If-Modified-Since", "Fri, 02 Jan 2009 17:00:05 GMT"); con.setRequestProperty("If-None-Match", "\"1261d8-4290-df64d224\""); con.setRequestProperty("Cache-Control", "max-age=0"); con.setRequestProperty("Referer", "http://www.dianping.com");
本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!