随笔-14  评论-0  文章-6  trackbacks-0
  2008年1月23日
Oracle SYNONYM

同义词 synonym

CREATE [PUBLIC]SYNONYM synonym For schema.object

隐藏对象的名称和所有者:
select count(*) from hr.employees;
create synonym emp for hr.employees;    --默认属于donny用户,是donny的私有对象private
select count(*) from emp;

为分布式数据库的远程对象提供了位置透明性:
访问其他数据库时,要首先建立数据库连结:
CREATE DATABASE LINK test_link CONNECT TO username IDENTIFIED BY pass USING 'orabase';
Select count(*) from hr.employees@test_link;
create synonym link_emp for hr.employees@test_link;
select count(*) from link_emp;

提供对象的公共访问:
create public synonym pub_emp for hr.employees;
pub_emp属于public用户,数据库所有用户都可以访问。

同义词类型
–私有 emp    实际上donny.emp
–公用 pub_emp   所有用户都可以直接访问

当公有对象和私有对象同名时(因为数据不同的用户,所以可以),以私有对象优先。(类似于局部变量)
desc   dba_synonyms/ user_synonyms/ all_synonyms 数据字典,复数
tab公有同义词
建立私有的tab表,查看效果。

删除同义词:
drop synonym donny.emp;
drop public synonym pub_emp;

 

 

 


序列sequence:
CREATE SEQUENCE donny.seq  --也是属于某个用户的,以下参数均可省略,使用默认值。
INCREMENT BY 1 --指定序列之间的间隔,正负整数;默认1,正为升序,负为降序。
START WITH 1 --第一个序列号,默认=MINVALUE
NOMAXVALUE --设置最大值,此处表示默认10的27次幂。MAXVALUE 10
NOMINVALUE --设置最小值,此处表示默认-10的26次幂。MINVALUE 1
NOCYCLE   --或者CYCLE;表示序列达到最大或者最小(降序)后,要不要从头开始
CACHE 10;   --默认CACHE 20, 事先分配多少序列号放在内存中,提高速度。

访问序列:
oracle为序列提供了两个伪列,可以看作其属性。
Nextval: 根据increment by得到的一个新的序列值。每次执行都会得到一个新值。
Currval: current value, 当前值,已经被取得的值。

Select seq.nextval from dual;
Select seq.currval from dual;

使用序列:
insert into t values(seq.nextval);

修改序列:
alter sequence seq …..重新指定各个参数
不能修改start with;除非删除重建

删除序列:
drop sequence seq;

数据字典:
desc dba_sequences / user_…/ all….


视图view:
CREATE [OR REPLACE][FORCE/ NOFORCE] VIEW <view_name> AS <query>

Create view mytable
As
Select first_name||’,’||last_name
from hr.employees;

[试验]:如何使用视图作为安全机制
1. desc考察hr.employees,看作一个公司的员工信息数据库表,简单说明
2. 目标:实现每个员工都可以访问公司中所有雇员的name, email, phone_number,方便通讯
3. 方案:
a) 赋予所有员工访问hr.employees表的权限?salary
b) 建立一个只包含合适字段的视图,然后赋予所有员工访问这个视图的权限,而不是表的权限。
4. Alter user hr account unlock;
Conn hr/hr
Create view company_phone_book as
Select first_name||’, ’||last_name name, email, phone_number
From employees;

Grant select on company_phone_book to public;

Desc company_phone_book   对比列的长度

Select * from company_phone_book;

name隐藏数据的复杂性

数据字典:
dba_views
text字段,long

select text from dba_views where view_name=upper(’company_phone_book’)

改变视图定义:
新需求:想要在现有视图上增加员工的ID号(employee_id)
Create view company_phone_book as
Select employee_id emp_id,
first_name||’,’||last_name name, email, phone_number
From employees;
报错;
如果删掉重建,会有什么缺点?会把关联的授权全部删掉。Create or replace view保留原有授权。
Create or replace view company_phone_book as
Select employee_id emp_id,
first_name||’,’||last_name name, email, phone_number
From employees;

Desc company_phone_book
Drop view company_phone_book

视图中增加约束:
create view yearly_hire_totals as
select to_char(hire_date,’YYYY’) year,
count(*) total
from hr.employees
group by to_char(hire_date,’YYYY’)
order by to_char(hire_date,’YYYY’);


联接视图:
desc hr.emp_details_view

set long 5000
select text from dba_views where view_name=upper(‘emp_details_view’)

with read only

验证视图有效性:
基本表的一些改变可能会导致视图无效:
1) 改变出现在视图中列的名称,或删掉列
2) 删除构建视图的基本表或视图

[试验]使视图无效,并重新编译并使其有效:
1) 基本表:create table base(id number,data varchar2(200));
insert into base values(1,’abc’); commit;
2) view:     create view view_b as
select id view_id, data view_data from t;
   
    select * from view_b;
3) 更新基本表: alter table base modify(id number,data varchar2(255));
     alter table base add(data2 varchar2(100));

4) 视图无效:select object_name, status from dba_objects where object_name=upper(‘view_b’)
5) 使视图有效:只需要从视图中选取即可, oracle会自动对视图编译
select * from view_b;
6) 手动编译: alter view view_b compile;

FORCE 选项:
强制ORACLE接受无效的视图定义:
1) 比如开发过程中A负责建立基本表,B负责建立视图。这样B不必依赖于A的工作进度就可以将视图建立并编译进数据库。
2) 或者B需要建立在A用户表上视图,但是还暂时没有对A用户表select 的权限,可以先建立,等待授权后再使用。
Create view invalid_view as
Select * from table_not_exist;
Create force view invalid_view as
Select * from table_not_exist;


通过视图进行更新和删除:
类似于company_phone_book是可以跟新的。
可以通过dba_updatable_columns查看那些列可以做那些更新;
desc hr.company_phone_book
select * from dba_updatable_columns where table_name=upper(‘company_phone_book’)

尝试更新email和name
update hr.company_phone_book
set name=’Chen, Donny’
where emp_id=100

1. 使用instead of 触发器更新视图:
create trigger update_name_company_phone_book
INSTEAD OF
Update on hr.company_phone_book
Begin
Update hr.employees
   Set employee_id=:new.emp_id,
    First_name=substr(:new.name, instr(:new.name,’,’)+2),
    last_name= substr(:new.name,1,instr(:new.name,’,’)-1),
    phone_number=:new.phone_number,
    email=:new.email
where employee_id=:old.emp_id;
end;


2. With check option 约束:
作用:阻止更新不能通过视图访问的数据。

试验:
1) 建立视图,只能看到department_id=10的雇员
create view department_10 as
select * from hr.employees where department_id=10
With check option
2) 选择:select employee_id,first_name,last_name from department_10;
3) 查看可更新列:
select * from dba_updatable_columns
where table_name=upper(‘department_10’)
4) 尝试将此人移动到部门20
update department_10
   set department_id=20
   where employee_id=200
报错!!
这个视图限制我们只能访问department=10的数据,我们要通过视图修改department=20的数据,被禁止。

[试验]关于前5名
1) 谁是公司前5名的雇员
select last_name,hire_date
from hr.employees
order by hire_date;
2) 只想取回前五名数据呢?
select last_name,hire_date
from hr.employees
where rownum<6
order by hire_date;
结果不正确,先取了前5条数据,再排序
3)select last_name,hire_date
from (select last_name,hire_date
from hr.employees
order by hire_date)
where rownum<6

posted @ 2008-01-23 10:14 高远 阅读(1932) | 评论 (0)编辑 收藏
  2007年1月16日

String 与 StringBuffer 的效率比较

看看以下代码:
将26个英文字母重复加了5000次,

String tempstr = "abcdefghijklmnopqrstuvwxyz";
int times = 5000;
long lstart1=System.currentTimeMillis();
  String str ="";
  for(int i=0;i<times;i++)
  {
   str+=tempstr;
  }
  
  long lend1=System.currentTimeMillis();
  long time = (lend1-lstart1);
  System.out.println(time);

可惜我的计算机不是超级计算机,得到的结果每次不一定一样一般为 154735 左右。
也就是154秒。
我们再看看以下代码

String tempstr = "abcdefghijklmnopqrstuvwxyz";
 
  int times = 5000;
long lstart2=System.currentTimeMillis();
  StringBuffer sb =new  StringBuffer();
  for(int i=0;i<times;i++)
  {
   sb.append(tempstr);
   
  }
  long lend2=System.currentTimeMillis();
  long time2 = (lend2-lstart2);
  System.out.println(time2);
 得到的结果为 16 有时还是 0
所以结论很明显,StringBuffer 的速度几乎是String 上万倍。当然这个数据不是很准确。因为循环的次数在100000次的时候,差异更大。不信你试试。
下一次我将解释为什么StringBuffer 的效率比String 高这么多。

posted @ 2007-01-16 11:33 高远 阅读(119) | 评论 (0)编辑 收藏
  2007年1月11日

有蓝图有计划——有蓝图,有计划,才能多人协同做事。

今日事今日毕——说起来容易,做起来绝对很难,但这恐怕是提高效能的最重要一环。相应的还有,做一件事就做完,不同时做几件事。

快速行动——实在有点厌烦了缓慢,当周一谈一个事项,别人告诉你下周一再说,那种感觉实在不好。

积极主动——以前总是不想推动别人做事,所以和主动做事的人合作做事效果最好。不过,新一年要变变了,如果不主动推动,好多事情做不成。

由内向外——工作的性质使得,与外界交流的要多多加强。

posted @ 2007-01-11 10:23 高远| 编辑 收藏
  2006年4月7日

在struts中分页的一种实现
liyun5889 转贴  (参与分:18011,专家分:1589)   发表:2005-03-07 19:10   版本:1.0   阅读:1905次


作者:未知     文章来源:http://www.jspcn.net/
访问次数: 次    加入时间:2005-01-19

在struts中分页的一种实现

我的项目中的分页功能
1, 思路
使用一个页面控制类,它记录页面信息,如上页,下页,当前页等。在查询的Action中,将这个控制类和查询条件一用数据库访问的bean,然后将这两个参数保存在用户session中。在分页控制Action中,利用接收到的分页参数调用数据库访问的bean.


2,实现

(1)分页控制类
/* @author nick
* Created on 2004-3-18
* file name:PageController.java
*
*
*/
package com.tower.util;

/**
* @author nick
* 2004-3-18
* 用来进行翻页控制
*
*/
public class PageController {
int totalRowsAmount; //总行数
boolean rowsAmountSet; //是否设置过totalRowsAmount
int pageSize=2; //每页行数
int currentPage=1; //当前页码
int nextPage;
int previousPage;
int totalPages; //总页数
boolean hasNext; //是否有下一页
boolean hasPrevious; //是否有前一页
String description;
int pageStartRow;
int pageEndRow;

public PageController(int totalRows){
setTotalRowsAmount(totalRows);
}
public PageController(){}

 

 

/**
* @param i
* 设定总行数
*/
public void setTotalRowsAmount(int i) {
if(!this.rowsAmountSet){
totalRowsAmount = i;
totalPages=totalRowsAmount/pageSize+1;
setCurrentPage(1);
this.rowsAmountSet=true;
}

}

/**
* @param i
*
* 当前页
*
*/
public void setCurrentPage(int i) {
currentPage = i;
nextPage=currentPage+1;
previousPage=currentPage-1;
//计算当前页开始行和结束行
if(currentPage*pageSize<totalRowsAmount){
pageEndRow=currentPage*pageSize;
pageStartRow=pageEndRow-pageSize+1;

}else{
pageEndRow=totalRowsAmount;
pageStartRow=pageSize*(totalPages-1)+1;
}


//是否存在前页和后页

if (nextPage>totalPages){
hasNext=false;
}else{
hasNext=true;
}
if(previousPage==0){
hasPrevious=false;
}else{
hasPrevious=true;
};
System.out.println(this.description());
}

/**
* @return
*/
public int getCurrentPage() {
return currentPage;
}

/**
* @return
*/
public boolean isHasNext() {
return hasNext;
}

/**
* @return
*/
public boolean isHasPrevious() {
return hasPrevious;
}

/**
* @return
*/
public int getNextPage() {
return nextPage;
}

/**
* @return
*/
public int getPageSize() {
return pageSize;
}

/**
* @return
*/
public int getPreviousPage() {
return previousPage;
}

/**
* @return
*/
public int getTotalPages() {
return totalPages;
}

/**
* @return
*/
public int getTotalRowsAmount() {
return totalRowsAmount;
}

/**
* @param b
*/
public void setHasNext(boolean b) {
hasNext = b;
}

/**
* @param b
*/
public void setHasPrevious(boolean b) {
hasPrevious = b;
}

/**
* @param i
*/
public void setNextPage(int i) {
nextPage = i;
}

/**
* @param i
*/
public void setPageSize(int i) {
pageSize = i;
}

/**
* @param i
*/
public void setPreviousPage(int i) {
previousPage = i;
}

/**
* @param i
*/
public void setTotalPages(int i) {
totalPages = i;
}
/**
* @return
*/
public int getPageEndRow() {
return pageEndRow;
}

/**
* @return
*/
public int getPageStartRow() {
return pageStartRow;
}

public String getDescription(){
String description="Total:"+this.getTotalRowsAmount()+
" items "+this.getTotalPages() +" pages";
// this.currentPage+" Previous "+this.hasPrevious +
// " Next:"+this.hasNext+
// " start row:"+this.pageStartRow+
// " end row:"+this.pageEndRow;
return description;
}

public String description(){
String description="Total:"+this.getTotalRowsAmount()+
" items "+this.getTotalPages() +" pages,Current page:"+
this.currentPage+" Previous "+this.hasPrevious +
" Next:"+this.hasNext+
" start row:"+this.pageStartRow+
" end row:"+this.pageEndRow;
return description;
}


public static void main(String args[]){
PageController pc=new PageController(3);
System.out.println(pc.getDescription());
// pc.setCurrentPage(2);
// System.out.println(pc.description());
// pc.setCurrentPage(3);
// System.out.println(pc.description());
}


}

(2)查询Action的代码片断

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
Base queryForm= (Base) form;

if(!queryForm.getName().equals("")){

PageController pc=new PageController();
EmployeeBase service=new EmployeeBase();
ArrayList result=(ArrayList)service.search(queryForm,pc);

HttpSession session=request.getSession();

session.setAttribute("queryForm",queryForm);
session.setAttribute("pageController",service.getPageController());

request.setAttribute("queryResult",result);
request.setAttribute("pageController",service.getPageController());
return mapping.findForward("haveResult");
}else{
return mapping.findForward("noResult");
}

 


}

(3),翻页Action的代码片断

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {


//读取翻页参数

TurnPageForm turnPageForm=(TurnPageForm)form;

//从PageController中取出查询信息,并使用bean提供的调用接口处理结果

HttpSession session=request.getSession();
PageController pc=(PageController)session.getAttribute("pageController");
Base queryForm=(Base)session.getAttribute("queryForm");


pc.setCurrentPage(turnPageForm.getViewPage());

EmployeeBase service=new EmployeeBase();

ArrayList result=(ArrayList)service.search(queryForm,pc);

//根据参数将数据写入 request

request.removeAttribute("queryResult");
request.removeAttribute("pageController");
request.setAttribute("queryResult",result);
request.setAttribute("pageController",pc);

//forward 到显示页面

 

return mapping.findForward("haveResult");

 

 

}

(4)数据库访问bean中的片断

public Collection search(Base base, PageController pc)
throws SQLException {
ArrayList emps = new ArrayList();
ResultSet rs = getSearchResult(base);

rs.absolute(-1);
pc.setTotalRowsAmount(rs.getRow());
setPageController(pc);
if (rs.getRow() > 0) {

rs.absolute(pc.getPageStartRow());


do {
System.out.println("in loop" + rs.getRow());

Base b = new Base();
b.setName(rs.getString("Name"));
b.setIdCard(rs.getString("IDCard"));
System.out.println("From db:" + rs.getString("IDCard"));
emps.add(b);
if (!rs.next()) {
break;
}
} while (rs.getRow() < (pc.getPageEndRow() + 1));
}
return emps;
}


(5)在jsp中,翻页部分的代码片断

<bean:write name="pageController" property="description"/>

<logic:equal name="pageController" property="hasPrevious" value="true">
<a href="turnPage.do?viewPage=<bean:write name="pageController" property="previousPage"/>" class="a02">
Previous
</a>
</logic:equal>

<logic:equal name="pageController" property="hasNext" value="true">
<a href="turnPage.do?viewPage=<bean:write name="pageController" property="nextPage"/>" class="a02">
Next
</a>
</logic:equal>

 

这样一来,翻页的功能可以以你喜欢的方式表现给client
 

posted @ 2006-04-07 16:48 高远 阅读(115) | 评论 (0)编辑 收藏

  Jakarta-Common-BeanUtils研究心得
一、概述
第一次看到BeanUtils包,是在Struts项目中,作为Struts一个工具来使用的,
估计功能越弄越强,就移到Common项目中了吧。

BeanUtils一共有四个package:
org.apache.commons.beanutils
org.apache.commons.beanutils.converters
org.apache.commons.beanutils.locale
org.apache.commons.beanutils.locale.converters
后三个包主要是用于数据的转换,围绕着一个Converter接口,该接口只有一个方法:
java.lang.Object convert(java.lang.Class type, java.lang.Object value) ,
用于将一个value转换成另一个类型为type的Object。在一些自动化的应用中应该会有用。
这里不作评论,以后有兴趣了,或者觉得有用了,再行研究。
这里只讲第一个包。

二、测试用的Bean
在开始所有的测试之前,我写了一个简单的Bean,以便于测试,代码如下:
package test.jakarta.commons.beanutils;

/**
* @author SonyMusic
*
*/
public class Month {
private int value;
private String name;
private int[] days={11,22,33,44,55};

public Month(int v, String n){
value=v;
name=n;
}

/**
* Returns the name.
* @return String
*/
public String getName() {
return name;
}

/**
* Returns the value.
* @return int
*/
public int getValue() {
return value;
}

/**
* Sets the name.
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* Sets the value.
* @param value The value to set
*/
public void setValue(int value) {
this.value = value;
}

/**
* @see java.lang.Object#toString()
*/
public String toString() {
return value+"("+name+")";
}

public int[] getDays() {
return days;
}

public void setDays(int[] is) {
days = is;
}

}

三、BeanUtils
这是一个主要应用于Bean的Util(呵呵,这个解释很绝吧),以下是其中几个方法的例子

//static java.util.Map describe(java.lang.Object bean)
//这个方法返回一个Object中所有的可读属性,并将属性名/属性值放入一个Map中,另外还有
//一个名为class的属性,属性值是Object的类名,事实上class是java.lang.Object的一个属性
Month month=new Month(1, "Jan");

try {
Map map=BeanUtils.describe(month);
Set keySet=map.keySet();
for (Iterator iter = keySet.iterator(); iter.hasNext();) {
Object element = (Object) iter.next();
System.out.println("KeyClass:"+element.getClass().getName());
System.out.println("ValueClass:"+map.get(element).getClass().getName());
System.out.print(element+"\t");
System.out.print(map.get(element));
System.out.println();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
输出为:
KeyClass:java.lang.String
ValueClass:java.lang.String
value 1
KeyClass:java.lang.String
ValueClass:java.lang.String
class class test.jakarta.commons.beanutils.Month
KeyClass:java.lang.String
ValueClass:java.lang.String
name Jan
注意到所有Map中的key/value都是String,而不管object中实际的值是多少。
与此对应的还有static void populate(java.lang.Object bean, java.util.Map properties)
用于将刚才describe出的Map再装配成一个对象。


再看这样一段代码
曹晓钢也许还记得,为了取一个不确定对象的property,着实花了不少时间,
难度不大,但要做到100%的正确,仍然需要付出很大的精力。
//static java.lang.String getProperty(java.lang.Object bean, java.lang.String name)
Month month=new Month(1, "Jan");

try {
System.out.println(BeanUtils.getProperty(month,"value"));
} catch (Exception e) {
e.printStackTrace();
}
//输出是:1

与getProperty类似的还有getIndexedProperty, getMappedProperty,
以getIndexedProperty为例:
Month month=new Month(1, "Jan");

try {
System.out.println(BeanUtils.getIndexedProperty(month,"days",1));
System.out.println(BeanUtils.getIndexedProperty(month,"days[1]"));
} catch (Exception e) {
e.printStackTrace();
}
这两个调用是相同的。


BeanUtils中还有一个方法:
static void copyProperties(java.lang.Object dest, java.lang.Object orig)
它真是太有用,还记得struts中满天飞的都是copyProperties,我甚至怀疑整个BeanUtils最初
是不是因为这个方法的需求才写出来的。
它将对象orig中的属性复制到dest中去。


四、PropertyUtils
这个类和BeanUtils类很多的方法在参数上都是相同的,但返回值不同。
BeanUtils着重于"Bean",返回值通常是String,而PropertyUtils着重于属性,
它的返回值通常是Object。


五、ConstructorUtils
这个类中的方法主要分成两种,一种是得到构造方法,一种是创建对象。
事实上多数时候得到构造方法的目的就是创建对象,这里只介绍一下创建对象。
//static java.lang.Object ConstructorUtils.invokeConstructor
//(java.lang.Class klass, java.lang.Object[] args)
//根据一个java.lang.Class以及相应的构造方法的参数,创建一个对象。
Object obj=ConstructorUtils.invokeConstructor(Month.class, {new Integer(1), "Jan"});
Month month=(Month)obj;
try {
System.out.println(BeanUtils.getProperty(month,"value"));
} catch (Exception e) {
e.printStackTrace();
}
输出证明,构造方法的调用是成功的。
如果需要强制指定构造方法的参数类型,可以这样调用:
Object[] args={new Integer(1), "Jan"};
Class[] argsType={int.class, String.class};
Object obj;
obj = ConstructorUtils.invokeExactConstructor(Month.class, args, argsType);
Month month=(Month)obj;
System.out.println(BeanUtils.getProperty(month,"value"));
argsType指定了参数的类型。

六、ConstructorUtils补遗
创建对象还有一个方法:invokeExactConstructor,该方法对参数要求
更加严格,传递进去的参数必须严格符合构造方法的参数列表。
例如:
Object[] args={new Integer(1), "Jan"};
Class[] argsType={int.class, String.class};
Object obj;
//下面这句调用将不会成功,因为args[0]的类型为Integer,而不是int
//obj = ConstructorUtils.invokeExactConstructor(Month.class, args);

//这一句就可以,因为argsType指定了类型。
obj = ConstructorUtils.invokeExactConstructor(Month.class, args, argsType);
Month month=(Month)obj;
System.out.println(BeanUtils.getProperty(month,"value"));


七、MethodUtils
与ConstructorUtils类似,不过调用的时候,通常需要再指定一个method name的参数。

八、DynaClass/DynaBean
这似乎是BeanUtils中最有趣的部分之一了,很简单,简单到光看这两个接口中的方法会不明白
为什么要设计这两个接口。不过看到ResultSetDynaClass后,就明白了。下面是java doc中的代码:
   ResultSet rs = ...;
   ResultSetDynaClass rsdc = new ResultSetDynaClass(rs);
   Iterator rows = rsdc.iterator();
   while (rows.hasNext())  {
     DynaBean row = (DynaBean) rows.next();
     ... process this row ...
   }
   rs.close();
原来这是一个ResultSet的包装器,ResultSetDynaClass实现了DynaClass,它的iterator方法返回一个
ResultSetIterator,则是实现了DynaBean接口。
在获得一个DynaBean之后,我们就可以用
     DynaBean row = (DynaBean) rows.next();
     System.out.println(row.get("field1")); //field1是其中一个字段的名字

再看另一个类RowSetDynaClass的用法,代码如下:
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost/2hu?useUnicode=true&characterEncoding=GBK";
String username="root";
String password="";

java.sql.Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url);
ps=con.prepareStatement("select * from forumlist");
rs=ps.executeQuery();
//先打印一下,用于检验后面的结果。
while(rs.next()){
System.out.println(rs.getString("name"));
}
rs.beforeFirst();//这里必须用beforeFirst,因为RowSetDynaClass只从当前位置向前滚动

RowSetDynaClass rsdc = new RowSetDynaClass(rs);
rs.close();
ps.close();
List rows = rsdc.getRows();//返回一个标准的List,存放的是DynaBean
for (int i = 0; i <rows.size(); i++) {
DynaBean b=(DynaBean)rows.get(i);
System.out.println(b.get("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
con.close();
} catch (Exception e) {
}
}

是不是很有趣?封装了ResultSet的数据,代价是占用内存。如果一个表有10万条记录,rsdc.getRows()
就会返回10万个记录。@_@

需要注意的是ResultSetDynaClass和RowSetDynaClass的不同之处:
1,ResultSetDynaClass是基于Iterator的,一次只返回一条记录,而RowSetDynaClass是基于
List的,一次性返回全部记录。直接影响是在数据比较多时ResultSetDynaClass会比较的快速,
而RowSetDynaClass需要将ResultSet中的全部数据都读出来(并存储在其内部),会占用过多的
内存,并且速度也会比较慢。
2,ResultSetDynaClass一次只处理一条记录,在处理完成之前,ResultSet不可以关闭。
3,ResultSetIterator的next()方法返回的DynaBean其实是指向其内部的一个固定
对象,在每次next()之后,内部的值都会被改变。这样做的目的是节约内存,如果你需要保存每
次生成的DynaBean,就需要创建另一个DynaBean,并将数据复制过去,下面也是java doc中的代码:
   ArrayList results = new ArrayList(); // To hold copied list
   ResultSetDynaClass rsdc = ...;
   DynaProperty properties[] = rsdc.getDynaProperties();
   BasicDynaClass bdc =
     new BasicDynaClass("foo", BasicDynaBean.class,
                        rsdc.getDynaProperties());
   Iterator rows = rsdc.iterator();
   while (rows.hasNext()) {
     DynaBean oldRow = (DynaBean) rows.next();
     DynaBean newRow = bdc.newInstance();
     PropertyUtils.copyProperties(newRow, oldRow);
     results.add(newRow);
   }

事实上DynaClass/DynaBean可以用于很多地方,存储各种类型的数据。自己想吧。嘿嘿。


九、自定义的CustomRowSetDynaClass
两年前写过一个与RowSetDynaClass目标相同的类,不过多一个功能,就是分页,只取需要的数据,
这样内存占用就会减少。

先看一段代码:
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost/2hu?useUnicode=true&characterEncoding=GBK";
String username="root";
String password="";

java.sql.Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url);
ps=con.prepareStatement("select * from forumlist order by name");
rs=ps.executeQuery();
/*
while(rs.next()){
System.out.println(rs.getString("name"));
}
rs.beforeFirst();
*/

//第二个参数表示第几页,第三个参数表示页的大小
CustomRowSetDynaClass rsdc = new CustomRowSetDynaClass(rs, 2, 5);
//RowSetDynaClass rsdc = new RowSetDynaClass(rs);
rs.close();
ps.close();
List rows = rsdc.getRows();
for (int i = 0; i <rows.size(); i++) {
DynaBean b=(DynaBean)rows.get(i);
System.out.println(b.get("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
con.close();
} catch (Exception e) {
}
}
在这里用到了一个CustomRowSetDynaClass类,构造方法中增加了page和pageSize两个参数,
这样,不管数据库里有多少条记录,最多只取pageSize条记录,若pageSize==-1,则功能和
RowSetDynaClass一样。这在大多数情况下是适用的。该类的代码如下:

package test.jakarta.commons.beanutils;

import java.io.*;
import java.sql.*;
import java.util.*;

import org.apache.commons.beanutils.*;

/**
* @author SonyMusic
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
public class CustomRowSetDynaClass implements DynaClass, Serializable {

// ----------------------------------------------------------- Constructors

/**
* <p>Construct a new {@link RowSetDynaClass} for the specified
* <code>ResultSet</code>.  The property names corresponding
* to column names in the result set will be lower cased.</p>
*
* @param resultSet The result set to be wrapped
*
* @exception NullPointerException if <code>resultSet</code>
*  is <code>null</code>
* @exception SQLException if the metadata for this result set
*  cannot be introspected
*/
public CustomRowSetDynaClass(ResultSet resultSet) throws SQLException {

this(resultSet, true);

}

/**
* <p>Construct a new {@link RowSetDynaClass} for the specified
* <code>ResultSet</code>.  The property names corresponding
* to the column names in the result set will be lower cased or not,
* depending on the specified <code>lowerCase</code> value.</p>
*
* <p><strong>WARNING</strong> - If you specify <code>false</code>
* for <code>lowerCase</code>, the returned property names will
* exactly match the column names returned by your JDBC driver.
* Because different drivers might return column names in different
* cases, the property names seen by your application will vary
* depending on which JDBC driver you are using.</p>
*
* @param resultSet The result set to be wrapped
* @param lowerCase Should property names be lower cased?
*
* @exception NullPointerException if <code>resultSet</code>
*  is <code>null</code>
* @exception SQLException if the metadata for this result set
*  cannot be introspected
*/
public CustomRowSetDynaClass(ResultSet resultSet, boolean lowerCase)
throws SQLException {

this(resultSet, 1, -1, lowerCase);

}

public CustomRowSetDynaClass(
ResultSet resultSet,
int page,
int pageSize,
boolean lowerCase)
throws SQLException {

if (resultSet == null) {
throw new NullPointerException();
}
this.lowerCase = lowerCase;
this.page = page;
this.pageSize = pageSize;

introspect(resultSet);
copy(resultSet);

}

public CustomRowSetDynaClass(ResultSet resultSet, int page, int pageSize)
throws SQLException {
this(resultSet, page, pageSize, true);
}

// ----------------------------------------------------- Instance Variables

/**
* <p>Flag defining whether column names should be lower cased when
* converted to property names.</p>
*/
protected boolean lowerCase = true;

protected int page = 1;
protected int pageSize = -1;

/**
* <p>The set of dynamic properties that are part of this
* {@link DynaClass}.</p>
*/
protected DynaProperty properties[] = null;

/**
* <p>The set of dynamic properties that are part of this
* {@link DynaClass}, keyed by the property name.  Individual descriptor
* instances will be the same instances as those in the
* <code>properties</code> list.</p>
*/
protected Map propertiesMap = new HashMap();

/**
* <p>The list of {@link DynaBean}s representing the contents of
* the original <code>ResultSet</code> on which this
* {@link RowSetDynaClass} was based.</p>
*/
protected List rows = new ArrayList();

// ------------------------------------------------------ DynaClass Methods

/**
* <p>Return the name of this DynaClass (analogous to the
* <code>getName()</code> method of <code>java.lang.Class</code), which
* allows the same <code>DynaClass</code> implementation class to support
* different dynamic classes, with different sets of properties.</p>
*/
public String getName() {

return (this.getClass().getName());

}

/**
* <p>Return a property descriptor for the specified property, if it
* exists; otherwise, return <code>null</code>.</p>
*
* @param name Name of the dynamic property for which a descriptor
*  is requested
*
* @exception IllegalArgumentException if no property name is specified
*/
public DynaProperty getDynaProperty(String name) {

if (name == null) {
throw new IllegalArgumentException("No property name specified");
}
return ((DynaProperty) propertiesMap.get(name));

}

/**
* <p>Return an array of <code>ProperyDescriptors</code> for the properties
* currently defined in this DynaClass.  If no properties are defined, a
* zero-length array will be returned.</p>
*/
public DynaProperty[] getDynaProperties() {

return (properties);

}

/**
* <p>Instantiate and return a new DynaBean instance, associated
* with this DynaClass.  <strong>NOTE</strong> - This operation is not
* supported, and throws an exception.</p>
*
* @exception IllegalAccessException if the Class or the appropriate
*  constructor is not accessible
* @exception InstantiationException if this Class represents an abstract
*  class, an array class, a primitive type, or void; or if instantiation
*  fails for some other reason
*/
public DynaBean newInstance()
throws IllegalAccessException, InstantiationException {

throw new UnsupportedOperationException("newInstance() not supported");

}

// --------------------------------------------------------- Public Methods

/**
* <p>Return a <code>List</code> containing the {@link DynaBean}s that
* represent the contents of each <code>Row</code> from the
* <code>ResultSet</code> that was the basis of this
* {@link RowSetDynaClass} instance.  These {@link DynaBean}s are
* disconnected from the database itself, so there is no problem with
* modifying the contents of the list, or the values of the properties
* of these {@link DynaBean}s.  However, it is the application's
* responsibility to persist any such changes back to the database,
* if it so desires.</p>
*/
public List getRows() {

return (this.rows);

}

// ------------------------------------------------------ Protected Methods

/**
* <p>Copy the column values for each row in the specified
* <code>ResultSet</code> into a newly created {@link DynaBean}, and add
* this bean to the list of {@link DynaBean}s that will later by
* returned by a call to <code>getRows()</code>.</p>
*
* @param resultSet The <code>ResultSet</code> whose data is to be
*  copied
*
* @exception SQLException if an error is encountered copying the data
*/
protected void copy(ResultSet resultSet) throws SQLException {
int abs = 0;
int rowsCount = 0;
int currentPageRows = 0;
resultSet.last();
rowsCount = resultSet.getRow();
if (pageSize != -1) {
int totalPages = (int) Math.ceil(((double) rowsCount) / pageSize);
if (page > totalPages)
page = totalPages;
if (page < 1)
page = 1;
abs = (page - 1) * pageSize;

//currentPageRows=(page==totalPages?rowsCount-pageSize*(totalPages-1):pageSize);
} else
pageSize = rowsCount;
if (abs == 0)
resultSet.beforeFirst();
else
resultSet.absolute(abs);
//int
while (resultSet.next() && ++currentPageRows <= pageSize) {
DynaBean bean = new BasicDynaBean(this);
for (int i = 0; i < properties.length; i++) {
String name = properties[i].getName();
bean.set(name, resultSet.getObject(name));
}
rows.add(bean);
}

}

/**
* <p>Introspect the metadata associated with our result set, and populate
* the <code>properties</code> and <code>propertiesMap</code> instance
* variables.</p>
*
* @param resultSet The <code>resultSet</code> whose metadata is to
*  be introspected
*
* @exception SQLException if an error is encountered processing the
*  result set metadata
*/
protected void introspect(ResultSet resultSet) throws SQLException {

// Accumulate an ordered list of DynaProperties
ArrayList list = new ArrayList();
ResultSetMetaData metadata = resultSet.getMetaData();
int n = metadata.getColumnCount();
for (int i = 1; i <= n; i++) { // JDBC is one-relative!
DynaProperty dynaProperty = createDynaProperty(metadata, i);
if (dynaProperty != null) {
list.add(dynaProperty);
}
}

// Convert this list into the internal data structures we need
properties =
(DynaProperty[]) list.toArray(new DynaProperty[list.size()]);
for (int i = 0; i < properties.length; i++) {
propertiesMap.put(properties[i].getName(), properties[i]);
}

}

/**
* <p>Factory method to create a new DynaProperty for the given index
* into the result set metadata.</p>
*
* @param metadata is the result set metadata
* @param i is the column index in the metadata
* @return the newly created DynaProperty instance
*/
protected DynaProperty createDynaProperty(
ResultSetMetaData metadata,
int i)
throws SQLException {

String name = null;
if (lowerCase) {
name = metadata.getColumnName(i).toLowerCase();
} else {
name = metadata.getColumnName(i);
}
String className = null;
try {
className = metadata.getColumnClassName(i);
} catch (SQLException e) {
// this is a patch for HsqlDb to ignore exceptions
// thrown by its metadata implementation
}

// Default to Object type if no class name could be retrieved
// from the metadata
Class clazz = Object.class;
if (className != null) {
clazz = loadClass(className);
}
return new DynaProperty(name, clazz);

}

/**
* <p>Loads and returns the <code>Class</code> of the given name.
* By default, a load from the thread context class loader is attempted.
* If there is no such class loader, the class loader used to load this
* class will be utilized.</p>
*
* @exception SQLException if an exception was thrown trying to load
*  the specified class
*/
protected Class loadClass(String className) throws SQLException {

try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = this.getClass().getClassLoader();
}
return (cl.loadClass(className));
} catch (Exception e) {
throw new SQLException(
"Cannot load column class '" + className + "': " + e);
}

}

}

posted @ 2006-04-07 16:47 高远 阅读(200) | 评论 (0)编辑 收藏

Java实现汉字转换为拼音本文的核心代码取自easydozer的blog:http://blog.csdn.net/easydozer/
代码说明:
Java实现汉字转换为拼音的GUI版本。

GUI代码部分:
/**
* @(#)CnToSpellGUI.java
* kindani
* 2004-10-25??
* */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

/**
*


*

JDK版本

1.4

* @author KIN
* @version 1.0
* @see
* @since 1.0
*/
public class CnToSpell2GUI extends JFrame {

private CnToSpell2GUI c = null;

public CnToSpell2GUI () {
super("Cn to Spell");
setSize(800,100);
getContentPane().setLayout(new FlowLayout());
// component layout
JTextArea from = new JTextArea(5,20);
JTextArea to = new JTextArea(5,20);
JButton b = new JButton("cn to pinyin");
getContentPane().add(new JLabel("From:"));
getContentPane().add(from);
getContentPane().add(b);
getContentPane().add(new JLabel("To:"));
getContentPane().add(to);
// action handle
b.addActionListener(new Cn2PinyinActionListener(from,to));
setVisible(true);
// set this for pack
c = this;
}

/**button action listener to convert text to pinyin from one textbox to another textbox*/
class Cn2PinyinActionListener implements ActionListener{

private JTextArea from = null;
private JTextArea to = null;
public Cn2PinyinActionListener(JTextArea from, JTextArea to) {
this.from = from;
this.to = to;
}
public void actionPerformed(ActionEvent e) {
if (from.getText().length() == 0) {
JOptionPane.showMessageDialog(from,"From text is empty!","Warning",JOptionPane.WARNING_MESSAGE);
}
String text = from.getText();
to.setText(CnToSpell.getFullSpell(text));
c.pack();
}
}

public static void main(String [] args) {
CnToSpell2GUI g = new CnToSpell2GUI();
}
}


核心代码部分:
引用自:easydozer的blog:http://blog.csdn.net/easydozer/
http://blog.csdn.net/easydozer/archive/2004/10/20/Chinese2FullSpell.aspx

 

/**
* @(#)CnToSpell.java
* 版权声明 Easydozer 版权所有 违者必究
*
* 修订记录:
* 1)更改者:Easydozer
* 时 间:2004-10-20 
* 描 述:创建
*/
package com.easydozer.commons.util;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

/**
*
汉字转化为全拼

*

JDK版本:

1.4

* @author 谢计生
* @version 1.0
* @see
* @since 1.0
*/
public class CnToSpell
{
private static LinkedHashMap spellMap = null;

static
{
if(spellMap == null){
spellMap = new LinkedHashMap(400);
}
initialize();
System.out.println("Chinese transfer Spell Done.");
}

private CnToSpell()
{
}

private static void spellPut(String spell,int ascii)
{
spellMap.put(spell,new Integer(ascii));
}

private static void initialize()
{
spellPut("a", -20319);
spellPut("ai", -20317);
spellPut("an", -20304);
spellPut("ang", -20295);
spellPut("ao", -20292);
spellPut("ba", -20283);
spellPut("bai", -20265);
spellPut("ban", -20257);
spellPut("bang", -20242);
spellPut("bao", -20230);
spellPut("bei", -20051);
spellPut("ben", -20036);
spellPut("beng", -20032);
spellPut("bi", -20026);
spellPut("bian", -20002);
spellPut("biao", -19990);
spellPut("bie", -19986);
spellPut("bin", -19982);
spellPut("bing", -19976);
spellPut("bo", -19805);
spellPut("bu", -19784);
spellPut("ca", -19775);
spellPut("cai", -19774);
spellPut("can", -19763);
spellPut("cang", -19756);
spellPut("cao", -19751);
spellPut("ce", -19746);
spellPut("ceng", -19741);
spellPut("cha", -19739);
spellPut("chai", -19728);
spellPut("chan", -19725);
spellPut("chang", -19715);
spellPut("chao", -19540);
spellPut("che", -19531);
spellPut("chen", -19525);
spellPut("cheng", -19515);
spellPut("chi", -19500);
spellPut("chong", -19484);
spellPut("chou", -19479);
spellPut("chu", -19467);
spellPut("chuai", -19289);
spellPut("chuan", -19288);
spellPut("chuang", -19281);
spellPut("chui", -19275);
spellPut("chun", -19270);
spellPut("chuo", -19263);
spellPut("ci", -19261);
spellPut("cong", -19249);
spellPut("cou", -19243);
spellPut("cu", -19242);
spellPut("cuan", -19238);
spellPut("cui", -19235);
spellPut("cun", -19227);
spellPut("cuo", -19224);
spellPut("da", -19218);
spellPut("dai", -19212);
spellPut("dan", -19038);
spellPut("dang", -19023);
spellPut("dao", -19018);
spellPut("de", -19006);
spellPut("deng", -19003);
spellPut("di", -18996);
spellPut("dian", -18977);
spellPut("diao", -18961);
spellPut("die", -18952);
spellPut("ding", -18783);
spellPut("diu", -18774);
spellPut("dong", -18773);
spellPut("dou", -18763);
spellPut("du", -18756);
spellPut("duan", -18741);
spellPut("dui", -18735);
spellPut("dun", -18731);
spellPut("duo", -18722);
spellPut("e", -18710);
spellPut("en", -18697);
spellPut("er", -18696);
spellPut("fa", -18526);
spellPut("fan", -18518);
spellPut("fang", -18501);
spellPut("fei", -18490);
spellPut("fen", -18478);
spellPut("feng", -18463);
spellPut("fo", -18448);
spellPut("fou", -18447);
spellPut("fu", -18446);
spellPut("ga", -18239);
spellPut("gai", -18237);
spellPut("gan", -18231);
spellPut("gang", -18220);
spellPut("gao", -18211);
spellPut("ge", -18201);
spellPut("gei", -18184);
spellPut("gen", -18183);
spellPut("geng", -18181);
spellPut("gong", -18012);
spellPut("gou", -17997);
spellPut("gu", -17988);
spellPut("gua", -17970);
spellPut("guai", -17964);
spellPut("guan", -17961);
spellPut("guang", -17950);
spellPut("gui", -17947);
spellPut("gun", -17931);
spellPut("guo", -17928);
spellPut("ha", -17922);
spellPut("hai", -17759);
spellPut("han", -17752);
spellPut("hang", -17733);
spellPut("hao", -17730);
spellPut("he", -17721);
spellPut("hei", -17703);
spellPut("hen", -17701);
spellPut("heng", -17697);
spellPut("hong", -17692);
spellPut("hou", -17683);
spellPut("hu", -17676);
spellPut("hua", -17496);
spellPut("huai", -17487);
spellPut("huan", -17482);
spellPut("huang", -17468);
spellPut("hui", -17454);
spellPut("hun", -17433);
spellPut("huo", -17427);
spellPut("ji", -17417);
spellPut("jia", -17202);
spellPut("jian", -17185);
spellPut("jiang", -16983);
spellPut("jiao", -16970);
spellPut("jie", -16942);
spellPut("jin", -16915);
spellPut("jing", -16733);
spellPut("jiong", -16708);
spellPut("jiu", -16706);
spellPut("ju", -16689);
spellPut("juan", -16664);
spellPut("jue", -16657);
spellPut("jun", -16647);
spellPut("ka", -16474);
spellPut("kai", -16470);
spellPut("kan", -16465);
spellPut("kang", -16459);
spellPut("kao", -16452);
spellPut("ke", -16448);
spellPut("ken", -16433);
spellPut("keng", -16429);
spellPut("kong", -16427);
spellPut("kou", -16423);
spellPut("ku", -16419);
spellPut("kua", -16412);
spellPut("kuai", -16407);
spellPut("kuan", -16403);
spellPut("kuang", -16401);
spellPut("kui", -16393);
spellPut("kun", -16220);
spellPut("kuo", -16216);
spellPut("la", -16212);
spellPut("lai", -16205);
spellPut("lan", -16202);
spellPut("lang", -16187);
spellPut("lao", -16180);
spellPut("le", -16171);
spellPut("lei", -16169);
spellPut("leng", -16158);
spellPut("li", -16155);
spellPut("lia", -15959);
spellPut("lian", -15958);
spellPut("liang", -15944);
spellPut("liao", -15933);
spellPut("lie", -15920);
spellPut("lin", -15915);
spellPut("ling", -15903);
spellPut("liu", -15889);
spellPut("long", -15878);
spellPut("lou", -15707);
spellPut("lu", -15701);
spellPut("lv", -15681);
spellPut("luan", -15667);
spellPut("lue", -15661);
spellPut("lun", -15659);
spellPut("luo", -15652);
spellPut("ma", -15640);
spellPut("mai", -15631);
spellPut("man", -15625);
spellPut("mang", -15454);
spellPut("mao", -15448);
spellPut("me", -15436);
spellPut("mei", -15435);
spellPut("men", -15419);
spellPut("meng", -15416);
spellPut("mi", -15408);
spellPut("mian", -15394);
spellPut("miao", -15385);
spellPut("mie", -15377);
spellPut("min", -15375);
spellPut("ming", -15369);
spellPut("miu", -15363);
spellPut("mo", -15362);
spellPut("mou", -15183);
spellPut("mu", -15180);
spellPut("na", -15165);
spellPut("nai", -15158);
spellPut("nan", -15153);
spellPut("nang", -15150);
spellPut("nao", -15149);
spellPut("ne", -15144);
spellPut("nei", -15143);
spellPut("nen", -15141);
spellPut("neng", -15140);
spellPut("ni", -15139);
spellPut("nian", -15128);
spellPut("niang", -15121);
spellPut("niao", -15119);
spellPut("nie", -15117);
spellPut("nin", -15110);
spellPut("ning", -15109);
spellPut("niu", -14941);
spellPut("nong", -14937);
spellPut("nu", -14933);
spellPut("nv", -14930);
spellPut("nuan", -14929);
spellPut("nue", -14928);
spellPut("nuo", -14926);
spellPut("o", -14922);
spellPut("ou", -14921);
spellPut("pa", -14914);
spellPut("pai", -14908);
spellPut("pan", -14902);
spellPut("pang", -14894);
spellPut("pao", -14889);
spellPut("pei", -14882);
spellPut("pen", -14873);
spellPut("peng", -14871);
spellPut("pi", -14857);
spellPut("pian", -14678);
spellPut("piao", -14674);
spellPut("pie", -14670);
spellPut("pin", -14668);
spellPut("ping", -14663);
spellPut("po", -14654);
spellPut("pu", -14645);
spellPut("qi", -14630);
spellPut("qia", -14594);
spellPut("qian", -14429);
spellPut("qiang", -14407);
spellPut("qiao", -14399);
spellPut("qie", -14384);
spellPut("qin", -14379);
spellPut("qing", -14368);
spellPut("qiong", -14355);
spellPut("qiu", -14353);
spellPut("qu", -14345);
spellPut("quan", -14170);
spellPut("que", -14159);
spellPut("qun", -14151);
spellPut("ran", -14149);
spellPut("rang", -14145);
spellPut("rao", -14140);
spellPut("re", -14137);
spellPut("ren", -14135);
spellPut("reng", -14125);
spellPut("ri", -14123);
spellPut("rong", -14122);
spellPut("rou", -14112);
spellPut("ru", -14109);
spellPut("ruan", -14099);
spellPut("rui", -14097);
spellPut("run", -14094);
spellPut("ruo", -14092);
spellPut("sa", -14090);
spellPut("sai", -14087);
spellPut("san", -14083);
spellPut("sang", -13917);
spellPut("sao", -13914);
spellPut("se", -13910);
spellPut("sen", -13907);
spellPut("seng", -13906);
spellPut("sha", -13905);
spellPut("shai", -13896);
spellPut("shan", -13894);
spellPut("shang", -13878);
spellPut("shao", -13870);
spellPut("she", -13859);
spellPut("shen", -13847);
spellPut("sheng", -13831);
spellPut("shi", -13658);
spellPut("shou", -13611);
spellPut("shu", -13601);
spellPut("shua", -13406);
spellPut("shuai", -13404);
spellPut("shuan", -13400);
spellPut("shuang", -13398);
spellPut("shui", -13395);
spellPut("shun", -13391);
spellPut("shuo", -13387);
spellPut("si", -13383);
spellPut("song", -13367);
spellPut("sou", -13359);
spellPut("su", -13356);
spellPut("suan", -13343);
spellPut("sui", -13340);
spellPut("sun", -13329);
spellPut("suo", -13326);
spellPut("ta", -13318);
spellPut("tai", -13147);
spellPut("tan", -13138);
spellPut("tang", -13120);
spellPut("tao", -13107);
spellPut("te", -13096);
spellPut("teng", -13095);
spellPut("ti", -13091);
spellPut("tian", -13076);
spellPut("tiao", -13068);
spellPut("tie", -13063);
spellPut("ting", -13060);
spellPut("tong", -12888);
spellPut("tou", -12875);
spellPut("tu", -12871);
spellPut("tuan", -12860);
spellPut("tui", -12858);
spellPut("tun", -12852);
spellPut("tuo", -12849);
spellPut("wa", -12838);
spellPut("wai", -12831);
spellPut("wan", -12829);
spellPut("wang", -12812);
spellPut("wei", -12802);
spellPut("wen", -12607);
spellPut("weng", -12597);
spellPut("wo", -12594);
spellPut("wu", -12585);
spellPut("xi", -12556);
spellPut("xia", -12359);
spellPut("xian", -12346);
spellPut("xiang", -12320);
spellPut("xiao", -12300);
spellPut("xie", -12120);
spellPut("xin", -12099);
spellPut("xing", -12089);
spellPut("xiong", -12074);
spellPut("xiu", -12067);
spellPut("xu", -12058);
spellPut("xuan", -12039);
spellPut("xue", -11867);
spellPut("xun", -11861);
spellPut("ya", -11847);
spellPut("yan", -11831);
spellPut("yang", -11798);
spellPut("yao", -11781);
spellPut("ye", -11604);
spellPut("yi", -11589);
spellPut("yin", -11536);
spellPut("ying", -11358);
spellPut("yo", -11340);
spellPut("yong", -11339);
spellPut("you", -11324);
spellPut("yu", -11303);
spellPut("yuan", -11097);
spellPut("yue", -11077);
spellPut("yun", -11067);
spellPut("za", -11055);
spellPut("zai", -11052);
spellPut("zan", -11045);
spellPut("zang", -11041);
spellPut("zao", -11038);
spellPut("ze", -11024);
spellPut("zei", -11020);
spellPut("zen", -11019);
spellPut("zeng", -11018);
spellPut("zha", -11014);
spellPut("zhai", -10838);
spellPut("zhan", -10832);
spellPut("zhang", -10815);
spellPut("zhao", -10800);
spellPut("zhe", -10790);
spellPut("zhen", -10780);
spellPut("zheng", -10764);
spellPut("zhi", -10587);
spellPut("zhong", -10544);
spellPut("zhou", -10533);
spellPut("zhu", -10519);
spellPut("zhua", -10331);
spellPut("zhuai", -10329);
spellPut("zhuan", -10328);
spellPut("zhuang", -10322);
spellPut("zhui", -10315);
spellPut("zhun", -10309);
spellPut("zhuo", -10307);
spellPut("zi", -10296);
spellPut("zong", -10281);
spellPut("zou", -10274);
spellPut("zu", -10270);
spellPut("zuan", -10262);
spellPut("zui", -10260);
spellPut("zun", -10256);
spellPut("zuo", -10254);
}

/**
* 获得单个汉字的Ascii.
* @param cn char
* 汉字字符
* @return int
* 错误返回 0,否则返回ascii
*/
public static int getCnAscii(char cn)
{
byte[] bytes = (String.valueOf(cn)).getBytes();
if(bytes == null || bytes.length > 2 || bytes.length <= 0){ //错误
return 0;
}
if(bytes.length == 1){ //英文字符
return bytes[0];
}
if(bytes.length == 2){ //中文字符
int hightByte = 256 + bytes[0];
int lowByte = 256 + bytes[1];

int ascii = (256 * hightByte + lowByte) - 256 * 256;

//System.out.println("ASCII=" + ascii);

return ascii;
}

return 0; //错误
}

/**
* 根据ASCII码到SpellMap中查找对应的拼音
* @param ascii int
* 字符对应的ASCII
* @return String
* 拼音,首先判断ASCII是否>0&<160,如果是返回对应的字符,
*
否则到SpellMap中查找,如果没有找到拼音,则返回null,如果找到则返回拼音.
*/
public static String getSpellByAscii(int ascii)
{
if(ascii > 0 && ascii < 160){ //单字符
return String.valueOf((char)ascii);
}

if(ascii < -20319 || ascii > -10247){ //不知道的字符
return null;
}

Set keySet = spellMap.keySet();
Iterator it = keySet.iterator();

String spell0 = null;;
String spell = null;

int asciiRang0 = -20319;
int asciiRang;
while(it.hasNext()){

spell = (String)it.next();
Object valObj = spellMap.get(spell);
if(valObj instanceof Integer){
asciiRang = ((Integer)valObj).intValue();

if(ascii >= asciiRang0 && ascii < asciiRang){ //区间找到
return(spell0 == null) ? spell : spell0;
}
else{
spell0 = spell;
asciiRang0 = asciiRang;
}
}
}

return null;

}

/**
* 返回字符串的全拼,是汉字转化为全拼,其它字符不进行转换
* @param cnStr String
* 字符串
* @return String
* 转换成全拼后的字符串
*/
public static String getFullSpell(String cnStr)
{
if(null == cnStr || "".equals(cnStr.trim())){
return cnStr;
}

char[] chars = cnStr.toCharArray();
StringBuffer retuBuf = new StringBuffer();
for(int i = 0,Len = chars.length;i < Len;i++){
int ascii = getCnAscii(chars[i]);
if(ascii == 0){ //取ascii时出错
retuBuf.append(chars[i]);
}
else{
String spell = getSpellByAscii(ascii);
if(spell == null){
retuBuf.append(chars[i]);
}
else{
retuBuf.append(spell);
} // end of if spell == null
} // end of if ascii <= -20400
} // end of for

return retuBuf.toString();
}

public static String getFirstSpell(String cnStr)
{
return null;
}

public static void main(String[] args)
{
String str = null;
str = "谢海101普降喜雨";
System.out.println("Spell=" + CnToSpell.getFullSpell(str));

str = "张牙舞爪》。,";
System.out.println("Spell=" + CnToSpell.getFullSpell(str));

str = "李鹏,可耻下场。";
System.out.println("Spell=" + CnToSpell.getFullSpell(str));

str = "猪油,猪八戒。";
System.out.println("Spell=" + CnToSpell.getFullSpell(str));
}
}

posted @ 2006-04-07 16:45 高远 阅读(364) | 评论 (0)编辑 收藏
仅列出标题  下一页