下载图片到本地

DownPicToLocalUtil.java

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
 
/**
 * 已知源图片路径,下载源图片到本地
 */
public class DownPicToLocalUtil {
	public static void main(String[] args) throws Exception {
		download("http://ui.51bi.com/opt/siteimg/images/fanbei0923/Mid_07.jpg","file://D:/download/downPic/","20180927163252529.png");
	}
 
	/**
	 * 下载源图片到本地
	 * 
	 * @param urlString
	 *            源图片路径
	 * @param savePath
	 *            本地存储路径
	 * @param filename
	 *            本地图片文件名
	 * @throws Exception
	 */
	public static int download(String urlString, String savePath,String filename) throws Exception {
		// 构造URL
		URL url = new URL(urlString);
		// 打开连接
		URLConnection con = url.openConnection();
		// 设置请求超时为5s
		con.setConnectTimeout(5 * 1000);
		// 输入流
		InputStream is = con.getInputStream();
		// 定义一个字节(1k)的数据缓冲区,该缓冲区的大小根据需要来定义
		byte[] buffer = new byte[1024];
		// 读取到的数据字节长度len
		int len;
                // 截取file://D:/download/downPic/为D:/download/downPic/
		String savePath_Format=savePath.substring(7,savePath.length());		
		// 创建file对象 savePath_Format可以为文件也可以为文件夹路径
		File savePath_File = new File(savePath_Format);
		// 判断文件或文件夹是否存在
		if (!savePath_File.exists()) {
			// 创建文件或者文件夹
			savePath_File.mkdirs();//或者savePath_File.createNewFile(); 
			System.out.println(savePath_File.getName() + " 创建成功");
		}else{
			System.out.println(savePath_File.getName() + " 已经存在");
		}
		// 输出的文件路径:自定义下载到的本地路径				
		String download_FilePath=savePath_File.getPath() + "\\" + filename;
		// 文件的输出流
		OutputStream os = new FileOutputStream(download_FilePath);
		// 循环读取该文件中的数据的文本内容content
		String content=null;
                // 将输入流以字节的形式读取并写入buffer中
		while ((len = is.read(buffer)) != -1) {//把数据先读到内存中
			//content=new String(buffer, 0, len);//可正常读取**.txt格式的输入文件 文本内容
			//System.out.println("数据:"+content);
			os.write(buffer, 0, len);//写到OutputStream中,每次都是从buffer内存处的0偏移开始写,每次写len字节	
		}
		// 若输出文件存在,则图片下载成功
		File download_File = new File(download_FilePath);
		int back=0;
		if(download_File.exists()){
			back=1;
		}
		System.out.println("成功下载"+back+"个文件:"+filename+"\n");
		// 关闭此文件输入流并释放与此流有关的所有系统资源。 
		os.close();
		is.close();
		return back;
	}
}
 
/**
 * 参考 java 下载网络上的图片并保存到本地目录http://takeme.iteye.com/blog/1683380
 */

DownPicToLocalUtil.java》右键Run As》Java Application》查看控制台

 》查看图片下载到的本地路径

猜你喜欢

转载自blog.csdn.net/LaOngDaoxing/article/details/82886386