手把手教你用java完成文件、图片下载
package?Kj;
import?java.io.FileOutputStream;
import?java.io.InputStream;
import?java.io.OutputStream;
import?java.net.URL;
import?java.net.URLConnection;
import?java.util.zip.GZIPInputStream;
/**
?*?下載?工具類
?*?
?*?@author?wuming
?*/
public?class?Demo1?{
??????????????
?????
????/**
?????*?下載文件到本地
?????*?@author?wuming
?????*?@date?2021年11月23日?上午19:20:05
?????*?@param?urlString
?????*?@param?filename
?????*?@throws?Exception
?????*/
????public?static?void?download(String?urlString,?String?filename)?throws?Exception?{
????????URL?url?=?new?URL(urlString);//?構造URL
????????URLConnection?con?=?url.openConnection();//?打開連接
????????InputStream?is?=?con.getInputStream();//?輸入流
????????String?code?=?con.getHeaderField("Content-Encoding");
????????if?((null?!=?code)?&&?code.equals("gzip"))?{
????????????GZIPInputStream?gis?=?new?GZIPInputStream(is);
????????????//?1K的數據緩沖
????????????byte[]?bs?=?new?byte[1024];
????????????//?讀取到的數據長度
????????????int?len;
????????????//?輸出的文件流
????????????OutputStream?os?=?new?FileOutputStream(filename);
????????????//?開始讀取
????????????while?((len?=?gis.read(bs))?!=?-1)?{
????????????????os.write(bs,?0,?len);
????????????}
????????????//?完畢,關閉所有鏈接
????????????gis.close();
????????????os.close();
????????????is.close();
????????}?else?{
????????????//?1K的數據緩沖
????????????byte[]?bs?=?new?byte[1024];
????????????//?讀取到的數據長度
????????????int?len;
????????????//?輸出的文件流
????????????OutputStream?os?=?new?FileOutputStream(filename);
????????????//?開始讀取
????????????while?((len?=?is.read(bs))?!=?-1)?{
????????????????os.write(bs,?0,?len);
????????????}
????????????//?完畢,關閉所有鏈接
????????????os.close();
????????????is.close();
????????}
????}
?????
????public?static?void?main(String[]?args)?{
????????try?{
??????????//?download("https://img.vgc.cn/dc/file/bigpic/2019-08-16/06/06494614368.jpg",?"D:\\wg\\xiazia\\pic_txt_xiazia\\10.jpg");
??????????//?download("https://pcclient.download.youku.com/youkuclient/youkuclient_setup_8.0.9.11050.exe?spm=a2hcb.25507605.product.1&file=youkuclient_setup_8.0.9.11050.exe",?"D:\\wg\\xiazia\\pic_txt_xiazia\\1.exe");???????
??????????download("??https://www.cs.tsinghua.edu.cn/__local/4/A5/88/41B9242401AE4D1F19EA8519BB5_0EDFFEE5_34804.pdf",?"D:\\wg\\xiazia\\pic_txt_xiazia\\55.pdf");
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}
????}
?
}
//去D:\\wg\\xiazia\\pic_txt_xiazia看,完成。
總結
以上是生活随笔為你收集整理的手把手教你用java完成文件、图片下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BugkuCTF-WEB题程序员本地网站
- 下一篇: msyql之事务