public String downLoadText(String urlStr){StringBuffer sb=new StringBuffer();String line=null;BufferedReader buffer=null;try {//建立一個URL對象url=new URL(urlStr);//建立一個Http串連try {HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();//使用IO流讀取資料buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));while ((line = buffer.readLine()) != null) {sb.append(line);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return sb.toString();}
/** 該函數返回整形-1:代表下載檔案出錯。* 0:代表下載檔案成功* 1:代表下載檔案經存在*/public int downLoadFile(String urlStr,String path,String fileName){InputStream inputStream=null;GoToSDCard gotoSDCard=new GoToSDCard();if(gotoSDCard.isFileExist(path+fileName)){return 1;}else{try {url=new URL(urlStr);HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();InputStream inputStream=urlConn.getInputStream(); File resultFile=gotoSDCard.write2SDFromInput(path, fileName,inputStream);//將資料流儲存到SD卡當中if(resultFile==null){return -1;}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {inputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return 0;}
public class GoToSDCard {private String SDPATH=null;public String getSDPATH(){return SDPATH;}public GoToSDCard(){//得到當前外部存放裝置的目錄// SDCARDSDPATH=Environment.getExternalStorageDirectory()+"";System.out.println("SDPATH="+SDPATH);}/**在SD卡上建立檔案 */public File CreatSDFile(String fileNmae){File file =new File(SDPATH+fileNmae);try {file.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return file;}/** 在SD卡上建立目錄*/public File creatSDDir(String dirName){File dir=new File(SDPATH+dirName);if(!dir.exists()){dir.mkdirs();}return dir;}/**判斷SD卡上的檔案夾是否存在*/public boolean isFileExist(String fileName){File file =new File(SDPATH+fileName);return file.exists();}/**將一個InputSteam裡面的資料寫入到SD卡中 */public File write2SDFromInput(String path,String fileName,InputStream input){System.out.println("path="+path+";fileName="+fileName+";");File file =null;File folder=null;OutputStream output=null;try {folder=creatSDDir(path);System.out.println("folder="+folder);file=CreatSDFile(path+fileName);System.out.println("file="+file);output=new FileOutputStream(file);byte buffer[]=new byte[4*1024];while((input.read())!=-1){output.write(buffer);}output.flush();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try{output.close();}catch(Exception e){e.printStackTrace();}}return file;}}
<uses-permission android:name="android.permission.INTERNET"/>//從網路中下載檔案需要的許可權<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>//向SD卡需要加入的寫入權限