android通過網路下載檔案分2步:
1.建立網路連接擷取資料流;
2.建立檔案把資料流寫到檔案中即可。(簡單吧)
廢話不多說,上代碼:
網路處理類 HttpDownloader.java
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/***
* 通過http協議下載檔案
* ***/
public class HttpDownloader {
private URL url = null;欠款
public InputStream getInputStreamFormUrl(String urlStr)
throws MalformedURLException,IOException{
url = new URL(urlStr);
HttpURLConnection httpc = (HttpURLConnection)url.openConnection();
return httpc.getInputStream();
}
public String downloadText(String urlStr){
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader breader = null;
try{
url = new URL(urlStr);
HttpURLConnection httpc = (HttpURLConnection)url.openConnection();
InputStream inputs = httpc.getInputStream();
breader = new BufferedReader(new InputStreamReader(inputs));
while((line=breader.readLine())!=null){
sb.append(line);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
breader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return sb.toString();
}
public int downloadFile(String urlStr,String path,String name){
InputStream input = null;
try{
FileUtils fu = new FileUtils();
if(fu.isFileExist(path+name)){ // 是否存在檔案,如果存在返回1
return 1;
}else{
input = getInputStreamFormUrl(urlStr);
File f = fu.inputStream2File(path, name, input);軟體開發
if(f==null){
return -1; // 資料有異常的時候返回-1
}
input.close();
}
}catch(Exception e){
e.printStackTrace();
return -1;
}
return 0; // 資料正常的時候返回0
}
}