Tools.java 1.34 KB
package com.phxl.common.util;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;


public class Tools {

	public static void main(String[] args) throws Exception {
		String str = "http://yryz-upload.oss-cn-hangzhou.aliyuncs.com/headImage/65b3139c0c730d32e902279a152c6759.jpg";
		String ext=str.substring(str.lastIndexOf("/")+1);
	    System.out.println(ext);
		Tools dw = new Tools();
		dw.saveToFile(str, "F:\\profiles\\" + ext);
	}

	/**
	 * 根据网络地址保存图片
	 */
	public void saveToFile(String destUrl, String filePath) {
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		URL url = null;
		int BUFFER_SIZE = 1024;
		byte[] buf = new byte[BUFFER_SIZE];
		int size = 0;
		try {
			url = new URL(destUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());
			fos = new FileOutputStream(filePath);
			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			fos.flush();
		} catch (IOException e) {
		} catch (ClassCastException e) {
		} finally {
			try {
				fos.close();
				bis.close();
				httpUrl.disconnect();
			} catch (IOException e) {
			} catch (NullPointerException e) {
			}
		}
	}

}