从服务器读取图片放在本地硬盘上

相关代码

package com.mqp.clent;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 这个类的主要目的是从服务器端获取图片然后按照流的方式输出到那个盘符 1、通过GET方式从服务器端获取数据 2、通过POST方式向服务器端发送数据
 * 
 * @author Administrator
 * 
 */

public class GetImage {
	// 服务器的地址
	private final static String IMAGE_PATH = "http://192.168.0.108:8080/Http/sj.png";
	static InputStream in = null;
	static HttpURLConnection httpUrl = null;
	static FileOutputStream fileOut = null;

	// 从服务器的到流文
	public static InputStream getInputStream() {
		try {
			URL url = new URL(IMAGE_PATH);
			if (url != null) {
				httpUrl = (HttpURLConnection) url.openConnection();// 建立连接

				httpUrl.setConnectTimeout(10000);// 设置超时时间
				httpUrl.setRequestMethod("GET");
				httpUrl.setDoInput(true);// 设置输入方式

				int code = httpUrl.getResponseCode();// 得到服务器方返回的类型
				if (code == 200) {
					in = httpUrl.getInputStream();
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();// 关闭流
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return in;
	}

	// 将流文件输出出来
	public static void writeFileToDark() {
		InputStream input = getInputStream();
		BufferedOutputStream bos = null;
		// 指定输出的路径
		try {
			// test.png指的是输出的名字
			fileOut = new FileOutputStream("d://test//test.png");
			bos = new BufferedOutputStream(fileOut);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		byte data[] = new byte[1024];// 每次循环输出多少个字节
		int flag = 0;
		try {
			while ((flag = input.read(data)) != -1) {// 不等于-1就代表继续往下读
				bos.write(data, 0, flag);// 输出到指定的路径
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fileOut.close();// 写完后关闭流
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		writeFileToDark();
	}

}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值