訪問Internet和保存文件到SDCard上,首先要在mainifest.xml文件中加上下面的權限。 java
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>gettextfilestring(String url)獲取文本文件內容
public String gettextfilestring(String url){ InputStream input =getinputStream(url); StringBuffer sb = new StringBuffer(""); BufferedReader bfr = new BufferedReader(new InputStreamReader(input)); String line = ""; try { while((line=bfr.readLine())!=null){ sb.append(line); } } catch (IOException e) { toasterror("流文件讀寫錯誤"); e.printStackTrace(); }finally{ try { bfr.close(); } catch (IOException e) { toasterror("流文件未能正常關閉"); e.printStackTrace(); } } return sb.toString(); }downFiletoDecive(String url,String filename)方法下載文件到設備內存,下載的文件在應用的路徑file下
public void downFiletoDecive(String url,String filename){ if((url!=null&&!"".equals(url))&&(filename!=null&&!"".equals(filename))){ InputStream input = getinputStream(url); FileOutputStream outStream = null; try { outStream = c.openFileOutput(filename, Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE); int temp = 0; byte[] data = new byte[1024]; while((temp = input.read(data))!=-1){ outStream.write(data, 0, temp); } } catch (FileNotFoundException e) { toasterror("請傳入正確的上下文"); e.printStackTrace(); } catch (IOException e) { toastemessage("讀寫錯誤"); e.printStackTrace(); }finally{ try { outStream.flush(); outStream.close(); } catch (IOException e) { toasterror("流文件未能正常關閉"); e.printStackTrace(); } } } toastemessage("下載成功"); }downFiletoSDCard(String url,String path,String filename)下載文件到SDCard中,自定義保存路徑
public void downFiletoSDCard(String url,String path,String filename){ if((url!=null&&!"".equals(url))&&(path!=null)&&(filename!=null&&!"".equals(filename))){ InputStream input = getinputStream(url); downloader(input, path, filename); }else{ /* * 對不合發的參數作處理 */ if(url==null||"".equals(url)){ toasterror("url不能爲空或爲「」"); } if(path==null){ toasterror("path不能爲空"); } if(filename==null||"".equals(filename)){ toasterror("filename不能爲空"); } } }