天堂向右,我依然向左

天下之大,虽离家千里,何处不可往!何事不可为!
生活之路,纵坎坷曲折,当奋斗不息,则精彩纷呈!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
代码
    @Override
    
public void onCreate(Bundle savedInstanceState) {
        
super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        
if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File file 
= Environment.getExternalStorageDirectory();
            Log.i(TAG, 
"begin download:" + file.getPath());
            testDownload(file.getPath());
        }
    }

 private void testDownload(String filepath) {
  long breakPoint = 0;
  try {
   String localPath = filepath + "/oracle10g.zip";
   Log.i(TAG, "begin download:" + localPath);
   
   File file = new File(localPath);
   
   if (file.exists()) {
    breakPoint = file.length(); 
    Log.d(TAG, "breakPoint:" + breakPoint);
   }

   String targetURL = "http://10.1.31.231:8080/Message/oracle10g.zip";
   URL url = new URL(targetURL);
   HttpURLConnection httpConnection = (HttpURLConnection) url
     .openConnection();
   
   //判断是否已经下载完毕
   Map<String, List<String>> map = httpConnection.getHeaderFields();
   Iterator<?>  iter = map.entrySet().iterator();
   while (iter.hasNext()) {
       Map.Entry entry = (Map.Entry) iter.next();
       String key = (String) entry.getKey();
       List<String> list = (List<String>) entry.getValue();
       Log.i(TAG, "\r\nkey=" + key);
       for(String s : list) {
         Log.d(TAG, "value = " + s);
       }
   }
   if (breakPoint == Integer.parseInt( map.get("content-length").get(0) )) {
    Log.d(TAG, "已经下载完毕!");
    return;
   }
   

   // 下面告诉服务器从breakPoint开始发送过来,而不需要重头(第0字节)发送.
   httpConnection.setRequestProperty("RANGE", "bytes=" + breakPoint
     + "-");

   RandomAccessFile localFile = new RandomAccessFile(file, "rw");
   localFile.seek(breakPoint); // 跳到断点处再继续写文件...

 

   
   InputStream inputStream = httpConnection.getInputStream();
   byte[] bytes = new byte[2048];

   int currentRead = 0;
   while ((currentRead = inputStream.read(bytes, 0, 2048 - 1)) > 0)
   {
    localFile.write(bytes, 0, currentRead);
   }
  } catch (Exception e) {
   Log.e(TAG, e.toString());
   e.printStackTrace();
  }

 }


 

posted on 2010-11-10 12:05  老舟  阅读(200)  评论(0编辑  收藏  举报