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();
}
}
网名:@"老舟"
兴趣:@"影音,阅读"
动态:@"系统架构设计,Android通信模块开发"
网址:@"http://kilonet.cnblogs.com"
签名:@"--------------------------------------------------
Stay Hungry , Stay Foolish
求 知 若 渴,处 事 若 愚
--------------------------------------------------"
]; // Never Release