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

📄 textreader.java

📁 在J2ME中实现了文本的阅读功能
💻 JAVA
字号:
/*
 * TextReader.java
 *
 * Created on 2007年5月31日,下午11:12
 */

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author  Administrator
 * @version
 */
public class TextReader extends MIDlet {
    public void startApp() {
        display=Display.getDisplay(this);
        screen=new SplashScreen(this);
        screen.setDisplayTime(5000);
        display.setCurrent(screen);
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
    }
    
    public void quit(){
        destroyApp(true);
        notifyDestroyed();
    }
    private SplashScreen screen;
    private Display display;
}


/**
 * 闪屏类
 * @author hyj
 */
class SplashScreen extends Canvas{
    private TextReader parent;
    private SelectForm nextDisplay;
    private Timer timer=new Timer();
    private long displayTime=3000;          //闪屏显示时间
    private String message="MReader V1.0";
    
    public SplashScreen(TextReader midlet){
        parent=midlet;
    }
    
    public void paint(Graphics g){
        int width=this.getWidth();
        int height=this.getHeight();
        g.setColor(0x000000);
        g.fillRect(0,0,width,height);
        g.setColor(0x0000FF);
        g.fillArc(10,20,width-20,height-40,0,360);
        g.setColor(0xFFFFFF);
        g.drawArc(10,20,width-20,height-40,0,360);
        Font font=Font.getFont(Font.FACE_MONOSPACE,Font.STYLE_BOLD+Font.STYLE_ITALIC,Font.SIZE_LARGE);
        g.setFont(font);
        int msgWidth=font.stringWidth(message);
        int msgHeight=font.getHeight();
        g.drawString(message,(width-msgWidth)/2,(height-msgHeight)/2,Graphics.LEFT|Graphics.TOP);
    }
    
    public void setDisplayTime(long dispTime){
        displayTime=dispTime;
    }
    
    protected void keyPressed(int keyCode){
        disappear();
    }
    
    protected void pointerPressed(int y,int x){
        disappear();
    }
    
    private void disappear(){
        timer.cancel();
        nextDisplay=new SelectForm(parent);
        Display.getDisplay(parent).setCurrent(nextDisplay);
    }
    
    protected void showNotify(){
        timer.schedule(new TimerTask(){
            public void run(){
                disappear();
            }
        },displayTime);
    }
}

class TextPanel extends Canvas implements CommandListener,Runnable{
    TextPanel(TextReader midlet,SelectForm form,String file,int lang,String charset,int textColor,int backColor,int gridColor){
        this.setTitle("文本文件阅读器");
        parent=midlet;
        prev=form;
        filename=file;      //要打开的文件名称
        langcode=lang;      //文本语言代码
        encoding=charset;   //字符集
        quitCommand=new Command("返回",Command.EXIT,1);
        this.setTicker(new Ticker(file));
        this.addCommand(quitCommand);
        this.setCommandListener(this);
        
        scrWidth=this.getWidth();
        scrHeight=this.getHeight();
        font=Font.getFont(Font.FACE_MONOSPACE,Font.STYLE_BOLD,Font.SIZE_MEDIUM);
        
        rowHeight=font.getHeight()+3;       //设置行高为字符高度+3
        maxrows=scrHeight/rowHeight;        //计算最大行数
        left=2;
        top=(scrHeight-rowHeight*maxrows)/2;
        this.backColor=backColor;
        foreColor=textColor;
        borderColor=gridColor;
        Thread thread=new Thread(this);
        thread.start();
    }
    
    public void paint(Graphics g){
        this.setTitle("["+(rowNo+1)+"/"+rowcount+"]");      //显示活动文档名称
        clearScreen(g);             //清除屏幕
        drawBorder(g);              //编制边框
        g.setColor(foreColor);
        g.setFont(font);
        
        //以下循环显示当前一屏内容
        for(int i=rowNo;i<Math.min(rowNo+maxrows,rowcount);i++){
            String row=(String)rows.elementAt(i);
            g.drawString(row,left+2,top+(i-rowNo)*rowHeight+2,Graphics.LEFT|Graphics.TOP);
        }
    }
    
    private void clearScreen(Graphics g){
        g.setColor(backColor);
        g.fillRect(0,0,scrWidth,scrHeight);
        
    }
    private void drawBorder(Graphics g){
        g.setColor(borderColor);
        for(int i=0;i<=maxrows;i++){
            g.drawLine(left,top+i*rowHeight,left+scrWidth-4,top+i*rowHeight);
        }
    }
    public void commandAction(Command cmd,Displayable disp){
        if(cmd==quitCommand){
            Display.getDisplay(parent).setCurrent(prev);
        }
    }
    
    protected void keyPressed(int keyCode){
        int g=getGameAction(keyCode);
        if(g==Canvas.UP){       //按向上的键翻到上一行
            rowNo--;
            if(rowNo<0){
                rowNo=0;
            }
            repaint();
        }
        if(g==Canvas.DOWN){     //按向下的键翻到下一行
            rowNo++;
            if(rowNo>rowcount-maxrows){
                rowNo=rowcount-maxrows;
            }
            repaint();
        }
        if(g==Canvas.LEFT){     //按向左的键翻到上一页
            rowNo-=maxrows;
            if(rowNo<0){
                rowNo=0;
            }
            repaint();
        }
        if(g==Canvas.RIGHT){    //按向右的键翻到下一页
            rowNo+=maxrows;
            if(rowNo>rowcount-maxrows){
                rowNo=rowcount-maxrows;
            }
            repaint();
        }
    }
    
    public void run(){
        String url="file:///c:/predefgallery/predefphotos/"+filename;
        FileConnection conn=null;
        try{
            conn=(FileConnection)Connector.open(url,Connector.READ);        //打开文本文件
            DataInputStream in=conn.openDataInputStream();                  //打开数据输入流
            int size=in.available();                                        //检查文本文件大小
            byte[] buffer=new byte[size];                                   //创建文本缓冲区
            in.read(buffer);                                                //将所有内容读入缓冲区
            String content=new String(buffer,encoding);                     //用缓冲区中的内容创建字符串
            buffer=null;                                                    //释放缓冲区
            in.close();                                                     //关闭数据输入流
            conn.close();                                                   //关闭文本文件
            in=null;
            conn=null;
            rows=new Vector();                                              //用于保存所有文本行的向量
            int length=content.length();                                    //文本文件中内容总长度
            if(langcode==0){                                                //内容为中文
                maxcols=10;                                                 //一行最多显示十个汉字
            }
            else{                                                           //内容为英文
                maxcols=20;                                                 //一行最多显示二十个英文字符
            }
            
            /**
             * 以下代码处理字符串,将其拆分成合适宽度的行以便显示
             */
            int pos=0;              //起始位置为0
            rowcount=0;             //初始行数为0
            while(pos<length-maxcols){      //未到最后一行
                String text=content.substring(pos,pos+maxcols);             //取一行(20个)字符保存到text中
                int crlfpos=text.indexOf(13);                             //检查text是否包含换行符
                if(crlfpos>=0){                       //有换行符
                    text=text.substring(0,crlfpos);
                    pos=pos+crlfpos+2;
                }
                else{
                    pos=pos+maxcols;
                }
                rows.addElement(text);
                rowcount++;                 //行数累加

            }
            rows.addElement(content.substring(pos));        //将最后一行追加到行数据向量中
            rowcount++;                                     //行数加一
            
            
            rowNo=0;                                        //设置初始行号
            repaint();
        }catch(UnsupportedEncodingException uce){
            Alert ueErrMsg=new Alert("系统错误","系统不支持指定的字符集!",null,AlertType.ERROR);
            Display.getDisplay(parent).setCurrent(ueErrMsg);
        }catch(IOException ioe){
            Alert ioErrMsg=new Alert("系统错误","对不起,文件数据输入出现错误!",null,AlertType.ERROR);
            Display.getDisplay(parent).setCurrent(ioErrMsg);
        }catch(SecurityException se){
            Alert sErrMsg=new Alert("系统错误","对不起,因安全原因,本功能无法正确完成!",null,AlertType.ERROR);
            Display.getDisplay(parent).setCurrent(sErrMsg);
        }       
    }
        
    private TextReader parent;
    private SelectForm prev;
    private String filename;
    private int langcode;       //语言代码,0表示中文,1表示英文
    private String encoding;    //字符集代码
    private Command quitCommand;
    
    private int scrWidth,scrHeight,rowHeight,left,top,maxrows,maxcols;
    private int backColor,foreColor,borderColor;
    private Font font;
    
    private int rowcount,rowNo;     //行数,行号
    private Vector rows;            //行数据向量
}



class SelectForm extends Form implements CommandListener,Runnable {
    SelectForm(TextReader midlet){
        super("文本文件阅读器");
        parent=midlet;
        fileList=new ChoiceGroup("请选择文件",Choice.POPUP);
        langList=new ChoiceGroup("请指定语言",Choice.EXCLUSIVE);
        langList.append("中文",null);
        langList.append("英文",null);
        encList=new ChoiceGroup("请指定字符集",Choice.EXCLUSIVE);
        encList.append("GB2312",null);
        encList.append("UTF8",null);
        textColor=new TextField("请指定文字颜色","000000",6,TextField.ANY);
        backColor=new TextField("请指定背景颜色","FFFFFF",6,TextField.ANY);
        gridColor=new TextField("请指定线条颜色","FF0000",6,TextField.ANY);
        this.append(fileList);
        this.append(langList);
        this.append(encList);
        this.append(textColor);
        this.append(backColor);
        this.append(gridColor);
        okCommand=new Command("打开",Command.OK,1);
        exitCommand=new Command("退出",Command.EXIT,1);
        this.addCommand(okCommand);
        this.addCommand(exitCommand);
        this.setCommandListener(this);
        Thread thread=new Thread(this);
        thread.start();
    }
    
    public void commandAction(Command cmd,Displayable disp){
        if(cmd==okCommand){
            TextPanel reader=new TextPanel(parent,this,fileList.getString(fileList.getSelectedIndex()),langList.getSelectedIndex(),encList.getString(encList.getSelectedIndex()),Integer.parseInt(textColor.getString(),16),Integer.parseInt(backColor.getString(),16),Integer.parseInt(gridColor.getString(),16));
            Display.getDisplay(parent).setCurrent(reader);
        }
        if(cmd==exitCommand){
            parent.quit();
        }
    }
    
    public void run(){
        String fcMsg=System.getProperty("microedition.io.file.FileConnection.version");
        if(fcMsg==null){
            Alert fcErrMsg=new Alert("系统错误","对不起,您的手机不支持文件操作,无法实现本程序功能!",null,AlertType.ERROR);
            Display.getDisplay(parent).setCurrent(fcErrMsg);
        }
        else{
            String url="file:///c:/predefgallery/predefphotos/";
            //String url="file:///c:/";
            FileConnection conn=null;
            try{
                conn=(FileConnection)Connector.open(url,Connector.READ);        //打开文件夹
                Enumeration filelist=conn.list();                               //列举文件夹下所有文件
                while(filelist.hasMoreElements()){                              //依次将每个文本文件追加到文件列表中
                    String filename=(String)filelist.nextElement();
                    if(filename.substring(filename.length()-3).equalsIgnoreCase("txt")){    //如果文件扩展名为txt则加入文件列表
                        fileList.append(filename,null);
                    }
                }
                conn.close();                       //关闭文件夹
                conn=null;
            }catch(IOException ioe){
                Alert ioErrMsg=new Alert("系统错误","对不起,文件数据输入出现错误!",null,AlertType.ERROR);
                Display.getDisplay(parent).setCurrent(ioErrMsg);
            }catch(SecurityException se){
                Alert sErrMsg=new Alert("系统错误","对不起,因安全受限,本功能无法正确完成!",null,AlertType.ERROR);
                Display.getDisplay(parent).setCurrent(sErrMsg);
            }
        }
        
    }
    
    private TextReader parent;
    private Command okCommand,exitCommand;
    private ChoiceGroup fileList,langList,encList;
    private TextField textColor,backColor,gridColor;
    
}

⌨️ 快捷键说明

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