import java.io.*; import java.net.URL; import java.net.URLConnection; /** * 下載工具類 */ public class DownloadUtil { public static void download(String urlStr,String filename,String savePath) throws IOException { URL url = new URL(urlStr); //打開url鏈接 URLConnection connection = url.openConnection(); //請求超時時間 connection.setConnectTimeout(5000); //輸入流 InputStream in = connection.getInputStream(); //緩衝數據 byte [] bytes = new byte[1024]; //數據長度 int len; //文件 File file = new File(savePath); if(!file.exists()) file.mkdirs(); OutputStream out = new FileOutputStream(file.getPath()+"\\"+filename); //先讀到bytes中 while ((len=in.read(bytes))!=-1){ //再從bytes中寫入文件 out.write(bytes,0,len); } //關閉IO out.close(); in.close(); } }
更多資訊碼雲搜索 KakiNakajimajava