android通過指定的URL地址下載文件


public static String download(Context context,String docUrl)throws Exception{                           /***加載正文***/
        //獲取存儲卡路徑、構成保存文件的目標路徑
        String dirName = "";
        //SD卡具有讀寫權限、指定附件存儲路徑為SD卡上指定的文件夾        
        dirName = Environment.getExternalStorageDirectory()+"/Signature/";
        File f = new File(dirName);
        if(!f.exists()){      //判斷文件夾是否存在
            f.mkdir();        //如果不存在、則創建一個新的文件夾
        }
        //准備拼接新的文件名
        String[] list = docUrl.split("/");
        String fileName = list[list.length-1];
        fileName = dirName + fileName;
        File file = new File(fileName);
        if(file.exists()){    //如果目標文件已經存在
            file.delete();    //則刪除舊文件
        }
        //1K的數據緩沖
        byte[] bs = new byte[1024];
        //讀取到的數據長度
        int len;
        try{
            //通過文件地址構建url對象
            URL url = new URL(docUrl);
            //獲取鏈接
            //URLConnection conn = url.openConnection();
            //創建輸入流
            InputStream is = url.openStream();
            //獲取文件的長度
            //int contextLength = conn.getContentLength();        
            //輸出的文件流
            OutputStream os = new FileOutputStream(file);
            //開始讀取
            while((len = is.read(bs)) != -1){
                os.write(bs,0,len);
            }
            //完畢關閉所有連接
            os.close();
            is.close();
        }catch(MalformedURLException e){
            fileName = null;
            System.out.println("創建URL對象失敗");
            throw e;
        }catch(FileNotFoundException e){
            fileName = null;
            System.out.println("無法加載文件");
            throw e;
        }catch(IOException e){
            fileName = null;
            System.out.println("獲取連接失敗");
            throw e;
        }
        return fileName;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM