1.main函数中
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
/**
* @Description: 下载文件至本地
* @Author: wangyk
* @CreateDate: 2018/7/18 16:59
* @UpdateUser: wangyk
* @UpdateDate: 2018/7/18 16:59
* @UpdateRemark:
* @Version: 1.0
*/
public class InPutExercise
{
public static void main(String[] args) throws IOException
{
downloadBuffer("http://avatar.csdn.net/5/4/C/2_qq_35341771.jpg","F:/picture","mayi.png");
}
}
2.一个一个字节下载
/**
* @Description 下载图片
* @author wangyk
* @param urlPath 图片在的路径
* @param filePath 图片下载后保存的文件夹
* @param fileName 图片下载后保存的文件名
* @return void
* @exception
* @date 2018/7/18 17:06
*/
public static void download(String urlPath,String filePath,String fileName) throws IOException
{
//MalformedURLException:畸形的URL
URL url= new URL(urlPath);
//取得连接,IOException
URLConnection con = url.openConnection();
//设置超时时间
con.setConnectTimeout(10*1000);
//取得文件的输入字节流
InputStream in= con.getInputStream();
//获得文件夹对象
File file=new File(filePath);
//判断文件夹是否存在
if(!file.exists())
{
//文件夹不存在则创建文件夹
file.mkdirs();
}
//文件的输出流,没有此文件默认直接创建
OutputStream out=new FileOutputStream(filePath+File.separator+fileName);
//将文件一个一个字节地读取出来,放在read里面,当返回-1时,说明文件读至末尾
int read;
while ((read=in.read())!=-1)
{
//将read写入输出流
out.write(read);
}
//最后关闭输入输出流
out.close();
in.close();
}
3.缓冲字节下载
/**
* @Description 使用缓冲流下载图片
* @author wangyk
* @param urlPath
* @param filePath
* @param fileName
* @return void
* @exception
* @date 2018/7/18 17:11
*/
public static void downloadBuffer(String urlPath,String filePath,String fileName) throws IOException
{
//MalformedURLException:畸形的URL
URL url= new URL(urlPath);
//取得连接,IOException
URLConnection con = url.openConnection();
//设置超时时间
con.setConnectTimeout(10*1000);
//取得文件的输入字节流
InputStream in= con.getInputStream();
//获得文件夹对象
File file=new File(filePath);
//判断文件夹是否存在
if(!file.exists())
{
//文件夹不存在则创建文件夹
file.mkdirs();
}
//文件的输出流,没有此文件默认直接创建
OutputStream out=new FileOutputStream(filePath+File.separator+fileName);
//将文件一个一个字节地读取出来,放在read里面,当返回-1时,说明文件读至末尾
int read;
//设置缓冲512字节
byte[] buff=new byte[512];
while ((read=in.read(buff))!=-1)
{
//将read写入输出流
out.write(buff,0,buff.length);
}
//最后关闭输入输出流
out.close();
in.close();
}