demo下载地址 http://download.youkuaiyun.com/detail/h9911/8385923
其实不管是java还是android,都可以把输入输出流归为字节流和字符串流两种,一般的文字传输属于字符串流,而图片或者文件则属于字节流。
至于什么是字符串流和字节流,请查阅其他资料
废话不多说,直接上代码
记住先在AndroidManifest.xml中添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
package org.hpg.weather.download;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
String downloadUrl = "http://www.baidu.com/link?url=jg03OiD0qdTvFXqDAVPIN5DEnHjZbmC1obcgd1cZEKbDVLuWqCneKfp0TFLjdA7-7jok_S_Xcr2cuC898SDawODBDRHjQthP7PmAedG6srK";
String picUrl ="http://img01.mifile.cn/images/accs/xmjsb_11.jpg";
private Button downloadButton;
private ProgressBar progressBar ;
private int length = 0;
private TextView percentView ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadButton = (Button) findViewById(R.id.download);
percentView = (TextView) findViewById(R.id.percent);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setProgress(0);
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
download();
}
}).start();
}
});
}
//下载具体操作
private void download() {
int contentLength = 0;
try {
URL url = new URL(downloadUrl);
//打开连接
URLConnection conn = url.openConnection();
//打开输入流
InputStream is = conn.getInputStream();
//获得长度
contentLength = conn.getContentLength();
Log.e(TAG, "contentLength = " + contentLength);
//创建文件夹 MyDownLoad,在存储卡下
String dirName = Environment.getExternalStorageDirectory() + "/MyDownLoad/";
File file = new File(dirName);
//不存在创建
if (!file.exists()) {
file.mkdir();
}
//下载后的文件名
String fileName = dirName + "qq.apk";
File file1 = new File(fileName);
if (file1.exists()) {
file1.delete();
}
//创建字节流
byte[] bs = new byte[1024];
int len;
OutputStream os = new FileOutputStream(fileName);
//写数据
while ((len = is.read(bs)) != -1) {
length =length + len;
os.write(bs, 0, len);
Message message = handler.obtainMessage();
message.arg1 = 100 * length/contentLength;
handler.sendMessage(message);
}
//完成后关闭流
Log.e(TAG, "download-finish");
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//更新UI
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e(TAG,msg.arg1+"");
progressBar.setProgress(msg.arg1);
percentView.setText(msg.arg1+"%");
}
};
}
下面一个是后来的版本
String[] name = mUrl.split("/");
File file = new File(mPath);
// //如果已经下载直接打开在外部已经判断
// if (file.exists()) {
// mHandler.onSuccess(file);
// return;
// }
try {
URL url = new URL(mUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("GET");
//是否允许输入
connection.setDoInput(true);
//是否允许输出
connection.setDoOutput(false);
connection.setUseCaches(false);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//实现连接
connection.connect();
Log.e(TAG, "connection.getResponseCode()=" + connection.getResponseCode());
//连接失败
if (connection.getResponseCode() != 200) {
if (mHandler != null) {
mHandler.onFailed();
connection.disconnect();
}
return;
}
if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
//以下为下载操作
byte[] bytes = new byte[1];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
int len = is.read(bytes);
Log.e(TAG, len + "");
while (len > 0) {
bos.write(bytes);
len = is.read(bytes);
}
bos.close();
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.close();
//关闭网络连接
if (mHandler != null) {
mHandler.onSuccess(file);
}
connection.disconnect();
Log.e(TAG, "下载完成");
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}