相同的代码,为何写在单独的类里就会出问题

时间:2008-05-13 17:48:49   来源:论坛整理  作者:  编辑:chinaitzhe
Java code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/





import javax.microedition.io.*;

import java.io.*;



public class ReadRemote {

    private String strResult;

    private String url;

    private StringBuffer result;





    public ReadRemote(String url) {

        this.url = url;

    }



    public void readRemote() {

        HttpConnection hc = null;

        try {

            char ch;

                hc=(HttpConnection)Connector.open(url);   //运行时停滞在这里啦

            

            InputStreamReader isr=new InputStreamReader(hc.openInputStream(),"gb2312");



            while((ch=(char)isr.read())!=(char)-1){

                result.append(ch);

            }

 

        } catch (IOException e) {

            e.printStackTrace();

        }

        strResult=new String(result.toString());

    }



......






为什么写在class MyClass extends MIDlet里面就可以读到url的内容呢
网友回复:你的MIDlet这个里面有什么?
网友回复:
Java code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/





import javax.microedition.lcdui.*;

import javax.microedition.io.*;

import javax.microedition.midlet.*;

import java.io.*;





public class HttpRead extends MIDlet {

    private String url;

    private StringBuffer result;

    

    private Display display;

    private    TextBox t;

    public HttpRead() {

        url = "http://192.168.1.101/web/index.xml";

        display=Display.getDisplay(this);

        result=new StringBuffer();

    }

    public void startApp(){



        HttpConnection hc=null;

        try{

            char ch;

            hc=(HttpConnection)Connector.open(url);

            System.out.println(hc.toString());

            

            InputStreamReader isr=new InputStreamReader(hc.openInputStream(),"gb2312");



            while((ch=(char)isr.read())!=(char)-1){

                result.append(ch);

            }

        }catch(IOException e){

            e.printStackTrace();

        }catch(Throwable e){

            e.printStackTrace();

        }

        t=new TextBox("title",result.toString(),1000,0);

        display.setCurrent(t);

    }

    public void destroyApp(boolean nucondional){

        

    }

    public void pauseApp(){

        

    }

}


这个运行正常,可要是在里面实例化上面的ReadRemotel类,用ReadRemote的对象来访问url就停在Connector.open处了
网友回复:你可以把访问网络的程序写在线程里面在试试!
网友回复:char ch;

改成char ch=''或者char ch=null;

试下
关键字:相同,代码,写在,单独,问题,

文章评论

共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面