J2ME_下载图片

[code="java"]
package com.ming;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.ContentConnection;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
/*下载图片到手机
 * 无线联网技术   通用连接框架(GCF)
 */
public class DownloadImg extends MIDlet {
	private Display display;
	private Form f=new Form("下载图片");
	//初始化Connection
	ContentConnection connection=null;
	//初始化字节数组输出
	ByteArrayOutputStream bStm=null;
	//图片字节数组
	byte imageData[]=null;
	//数据输入流
	DataInputStream iStm=null;
	//初始化一张图片
	Image img=null;
	
	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		// TODO Auto-generated method stub

	}

	protected void pauseApp() {
		// TODO Auto-generated method stub

	}

	protected void startApp() throws MIDletStateChangeException {
		// TODO Auto-generated method stub
		display=Display.getDisplay(this);
                //链接地址(本机的TomCat服务器下的imgSite中名为mv.jpg的图片)
                String url="http://localhost:8080/imgSite/mv.jpg";
		getImage(url);//根据链接地址获取图片
		if (img!=null) {
			f.append(img);//加载显示图片
		}else {
			f.append("Error");
		}
		display.setCurrent(f);
	}

	//获取图片
	private void getImage(String url){
		try {
			//打开HTTP连接
			connection=(ContentConnection)Connector.open(url);
			//打开数据输入流
			iStm = connection.openDataInputStream();
			//Http连接长度
			int length=(int)connection.getLength();
			if (length!=-1) {
				//实例化图片字节数组
				imageData=new byte[length];
				//数据输入流完整读取图片字节数组
				iStm.readFully(imageData);
			}else{
				bStm=new ByteArrayOutputStream();
				int ch=iStm.read();
				while (ch!=-1) {
					bStm.write(ch);
					imageData=bStm.toByteArray();
				}
			}
			img=Image.createImage(imageData, 0,imageData.length);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//释放资源
			try {
				if (connection!=null) {connection.close();}
				if (iStm!=null) {iStm.close();}
				if (bStm!=null) {bStm.close();}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
}
[/code]

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值