⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httptxt.java

📁 《精通JAVA手机游戏与应用程序设计》随书光盘
💻 JAVA
字号:


import java.io.*;

import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class HttpTXT extends MIDlet implements CommandListener {

	private Command exitCommand, loadCommand;

	private Form mainForm;

	private TextField tfItem;

	private TextField tf;

	public HttpTXT() {
		mainForm = new Form("下载并显示文本文件");
		tf = new TextField("文本地址", "http://127.0.0.1:8080/TEST.txt", 120,
				TextField.URL);
		//设置控件的布局
		tf.setLayout(Item.LAYOUT_NEWLINE_AFTER);
		tfItem = new TextField("文本内容", "", 500,	TextField.ANY);
		tfItem.setPreferredSize(mainForm.getWidth(), 200);
		tfItem.setLayout(Item.LAYOUT_VEXPAND | Item.LAYOUT_2);

		mainForm.append(tf);
		mainForm.append(tfItem);

		exitCommand = new Command("退出", Command.EXIT, 1);
		loadCommand = new Command("下载", Command.SCREEN, 1);
		mainForm.addCommand(exitCommand);
		mainForm.addCommand(loadCommand);
		mainForm.setCommandListener(this);
	}

	protected void startApp() throws MIDletStateChangeException {
		Display.getDisplay(this).setCurrent(mainForm);
	}

	protected void pauseApp() {
	}

	protected void destroyApp(boolean p1) {
	}

	public void commandAction(Command c, Displayable d) {
		if (c == exitCommand) {
			destroyApp(false);
			notifyDestroyed();
		} else if (c == loadCommand) {
			//开启一个新的网络连接后台线程
			new DownLoadTXT(mainForm, tfItem, tf.getString());
		}
	}

	private class DownLoadTXT extends Thread {
		private String txtURL;

		private Form form; 

		private TextField tfItem; 

		public DownLoadTXT(Form f, TextField i, String url) {
			form = f;
			tfItem = i;
			txtURL = url;
			this.start();
		}

		public void run() {
			String str = null;
			try {
				str = getText(txtURL);
			} catch (Exception e) {
				System.out.println("错误 " + e.getMessage());
			}
			form.setTicker(null);
			if (tfItem != null)				
				tfItem.setString(str);
		}

		public String getText(String url) throws IOException, Exception {
			HttpConnection c = null;
			InputStream is = null;
			String str =null;
			try {
				c = (HttpConnection) Connector.open(url); 
				//判断是否连接成功
				int rc = c.getResponseCode(); 
				if (rc != HttpConnection.HTTP_OK) {
					throw new Exception(c.getResponseMessage());
				}
				//获得文本的二进制数据
				is = c.openInputStream();
				
				int length = (int) c.getLength();
				
				if (length > 0) {
					byte servletData[] = new byte[length];
					is.read(servletData);
					str = new String(servletData);
				}
								
				
			} catch (IOException e) {
				System.out.println("错误:" + e.getMessage());
			} finally {
				if (is != null)
					is.close();
				if (c != null)
					c.close();
			}
			return str;
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -