Java下载图片

通过java编程尝试从网络上下载一张图片,并保存到本地磁盘。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class TestURL {
	public static void main(String [] args) {
		String path = "http://patiencecats.com/ueditor/php/upload/image/20180312/1520829763554937.jpg";
		URL url = null;

		//从网络上下载一张图片
		InputStream inputStream = null;
		OutputStream outputStream = null;
		//建立一个网络链接
		HttpURLConnection con = null;
		try {
			url = new URL(path);
			con = (HttpURLConnection) url.openConnection();
			inputStream = con.getInputStream();
			outputStream = new FileOutputStream(new File("E:\\a.jpg"));
			int n = -1;
			byte b [] = new byte[1024];
			while ((n = inputStream.read(b)) != -1) {
				outputStream.write(b, 0, n);
			}
			outputStream.flush();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				inputStream.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				outputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}

你可能感兴趣的:(Java下载图片)