1. 程式人生 > 其它 >Java通過指定地址從伺服器下載檔案到本地

Java通過指定地址從伺服器下載檔案到本地

技術標籤:Javajava

Java通過指定地址從伺服器下載檔案到本地

萬能模板

	try {
			String downloadPath = "*******************************";
            //獲取檔名
            String filename = downloadPath.substring(downloadPath.lastIndexOf("\\")+1);
            // 解決中文亂碼
           /* filename = new String(filename.getBytes("ISO-8859-1"),"UTF-8");*/
File file = new File(downloadPath); //如果檔案不存在 if(!file.exists()){ return; } //設定響應頭,控制瀏覽器下載該檔案 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); //讀取要下載的檔案,儲存到檔案輸入流
in= new FileInputStream(downloadPath); //建立輸出流 out= response.getOutputStream(); //快取區 byte buffer[] = new byte[1024]; int len = 0; //迴圈將輸入流中的內容讀取到緩衝區中 while((len = in.read(buffer)) > 0){ out.write
(buffer, 0, len); } }finally { //關閉 in.close(); out.close(); }