首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

文本数据库的容易java实现

2012-09-22 
文本数据库的简单java实现?注:?转载请注明出处: http://hejiangtao.iteye.com ,?用于商业得给我分成这个是

文本数据库的简单java实现

?注:?转载请注明出处: http://hejiangtao.iteye.com ,?用于商业得给我分成文本数据库的容易java实现

这个是一个文本数据库简单的实现思路, 从这里可以下载到完整的java代码工程: ?http://download.csdn.net/detail/hejiangtao/3991735

什么人适合阅读本文:

1. 我自己平时写些小程序,存储数据使用那些收钱/开源的数据库太浪费电脑资源,直接存到文件里面更方便. 所以才搞了这个东东, 如果你和我有同样的苦恼和需求,你可以参考下,看有木有你需要的.?我简单把实现思路写了一下,需要的兄弟也可以参考下,根据情况自己做扩展或者封装文本数据库的容易java实现.

2.其中使用到了java泛型,java反射机制,文本输入输出等技术,如果想研究这些技术也可以参考这些代码,,看有么有你需要的.

? ?设计思路说明:

1.数据存相关规则

一般的数据库的存储规则是不暴露给用户的,如果使用文本来存储数据,用户可以随便修改,所以必须建立一定的规则,用户不能随意手动修改文本数据库内容. 我实现的时候是一个表,一个文本文件; 一个表对应一个Bean class, 并假设,Bean Class的名字就是文件名加Bean后缀, 列名和TableBean的域(Field)名是一样,这样可以轻松使用java反射机制; 文本文件的第一行有效列需指明列名和顺序,因为Field的顺序是不可控的,存在文本里面就可控了; 第一列为主键,列与列之间使用$_$分割.

2. 关键算法/设计

1)读写文件--数据肯定是多行的,所以使用buffered reader 和writer是必要的, 写入和读出数据的时候都按照一条记录一行的方式,方便解析

2)文本数据和Bean之间的转化--将数据存入Bean是为了更方便的解析和使用, 由于Bean的Class Name和Field Name及其Set/Get方法都是采用同样的命名方式,所以可以通过使用一个java泛型方法实现所有表/Bean的文本数据和Bean之间的转化,访问数据也可以java反射机制访问.

3)数据分析--由于文件内容分析只能在内存里面分析,如果数据量太大,只能先一部分一本的分析,将分析完的数据先写入到临时文件, 本例作为demo就按照全部写入内存方式来分析

?实现:

?整个工程的文件分布如下如图:

1.在工程主目录下的db下面是两个示例表的文件T_FamilyMember.db, T_Home.db, 后缀名是.db其实是文本

2.在包名com.ross.filedb下面, tablebean下是两张表对应的Bean,命名必须符合规则; util下是一些公共的业务不相关的一些操作实现或系统级变量; FileDBTool.java则实现了基本的增/删/改/查功能.

3. junit.ross.filedb下是简单的junit功能测试用例 (木有main,看运行结果请用junit看文本数据库的容易java实现)

文本数据库的容易java实现

? 先把Bean和db文件贴出来,命名是相互对应的,很明显,就不浪费口舌了:

T_Home.db:

?

?

[java] view plaincopy
  1. /**???????*?Author:?Jiangtao?He;?Email:?ross.jiangtao.he@gmail.com?
  2. ??????*?Description:????????*?1.?Get?the?string?of?new?record?which?will?be?save?to?DB?
  3. ??????*?2.?Since?the?object?is?a?generic?object,?so?the?reflect?mechanism?will?be????????*????used?to?access?the?data?of?the?bean.?
  4. ??????*?3.?assume?that?all?fields'nameof?the?bean?class?is?the?same?as????????*????the?columns'?name?of?table.?The?first?available?line?should?
  5. ??????*????give?the?columns'?sequence,?which?is?start?with?'ColumnSeq'.???????*????for?different?columns,?they?will?be?separated?by?'$_$'?
  6. ??????*?@param?oT:?the?object?of?bean????????*?@param?sFullFileName:?DB?file?name?with?completing?path?
  7. ??????*?@return?sRowData:?return?the?new?record?string???????*?@throws?IOException??
  8. ??????*?@throws?NoSuchMethodException????????*?@throws?SecurityException??
  9. ??????*?@throws?InvocationTargetException????????*?@throws?IllegalAccessException??
  10. ??????*?@throws?IllegalArgumentException????????*/??
  11. ??????private?<T>?String?convertBeantoStr(T?oT,?String?sFullFileName)??
  12. ????????????throws?IOException,?SecurityException,?NoSuchMethodException,??????????????IllegalArgumentException,?IllegalAccessException,??
  13. ????????????InvocationTargetException??????{??
  14. ????????//?define?the?return?value??????????String?sRowdata?=?"";??
  15. ??????????String[]?sColumns?=?null;??
  16. ????????BufferedReader?oBRead?=?null;??????????//?to?get?the?columns'?sequence??
  17. ????????try??????????{??
  18. ????????????oBRead?=?fileProcess.getBufferedFileReader(sFullFileName);??????????????String?sReadLine;??
  19. ????????????while?(null?!=?(sReadLine?=?oBRead.readLine()))??????????????{??
  20. ????????????????sReadLine?=?sReadLine.trim();??????????????????//?skip?the?comments?and?empty?lines??
  21. ????????????????if?("".equals(sReadLine)?||?sReadLine.startsWith("#"))??????????????????{??
  22. ????????????????????continue;??????????????????}??
  23. ??????????????????//?find?the?columns'?sequence??
  24. ????????????????if?(sReadLine.startsWith("ColumnSeq"))??????????????????{??
  25. ????????????????????sColumns?=?sReadLine.split(":")[1].split("\\$_\\$");??????????????????????break;??
  26. ????????????????}??????????????}??
  27. ????????}??????????catch?(IOException?e)??
  28. ????????{??????????????//?print?e,?and?throw?it,?so?the?method?which?invoked?it?can?process??
  29. ????????????//?it?freely.??????????????e.printStackTrace();??
  30. ????????????throw?e;??????????}??
  31. ????????finally??????????{??
  32. ????????????//?close?the?writer??????????????if?(null?!=?oBRead)??
  33. ????????????{??????????????????oBRead.close();??
  34. ????????????}??????????}??
  35. ??????????//?define?field?variable??
  36. ????????Method?oMethod?=?null;??????????String?sFieldName?=?"";??
  37. ????????String?sMethodName?=?"";??????????//?get?the?corresponding?columns'?value?through?the?reflect?mechanism??
  38. ????????for?(int?i?=?0;?i?<?sColumns.length;?i++)??????????{??
  39. ????????????//?initialize?the?method?name??????????????sMethodName?=?"get";??
  40. ????
  41. ????????????//?get?the?get?method?name?of?the?current?column??????????????sFieldName?=?sColumns[i].trim();??
  42. ????????????if?(sFieldName.length()?>?1)??????????????{??
  43. ????????????????sMethodName?=?sMethodName??????????????????????????+?sFieldName.substring(0,?1).toUpperCase()??
  44. ????????????????????????+?sFieldName.substring(1);??????????????}??
  45. ????????????else??????????????{??
  46. ????????????????sMethodName?=?sMethodName?+?sFieldName.toUpperCase();??????????????}??
  47. ????????????//?get?the?get?method??????????????oMethod?=?oT.getClass().getMethod(sMethodName);??
  48. ????????????//?Execute?the?method?to?get?the?value?of?the?current?field??????????????//?add?the?separator?of?the?columns?too??
  49. ????????????sRowdata?=?sRowdata?+?oMethod.invoke(oT)?+?"$_$";??????????}??
  50. ????????//?remove?the?last?separator??????????if?(!"".equals(sRowdata))??
  51. ????????{??????????????sRowdata?=?sRowdata.substring(0,?sRowdata.lastIndexOf("$_$"));??
  52. ????????}??????????return?sRowdata;??
  53. ????}??
3.有了上面两个步骤,就可以实现数据库记录的插入功能了

a. 这个insert方法的传入参数就是一个Table Bean的对象, 当然对象里面有你要存储到文本文件里的数据

b.根据这个Table Bean的对象获取带路径的完整文件名

c.将Bean转化成一条合格的字符串

d.将该字符串写入对应的DB文件的最后(为了保证数据在单独的一行,数据前先插入了换行符)

同样的,为了使所有的表Bean都可以通过这一个方法插入数据,将方法定义成了泛型方法.?

本方法并没有实现检查主键的工作,自己可以根据需要重载或封装实现.

?

[java] view plaincopy
  1. /**??????*?Author:?Jiangtao?He;?Email:?ross.jiangtao.he@gmail.com?
  2. ?????*?Description:?Insert?one?record?to?text?DB??????*?@param?oT:?the?object?of?bean??
  3. ?????*?@return?oResult:???????*??????????ResultBean.result:?true?-?insert?success;?false?-?insert?failed?
  4. ?????*??????????ResultBean.description:?the?description?of?the?result;??????*?@throws?IOException??
  5. ?????*?@throws?InvocationTargetException???????*?@throws?IllegalAccessException??
  6. ?????*?@throws?NoSuchMethodException???????*?@throws?IllegalArgumentException??
  7. ?????*?@throws?SecurityException???????*/??
  8. ????public?<T>?ResultBean?insert(T?oT)?throws?IOException,?SecurityException,??????????????IllegalArgumentException,?NoSuchMethodException,??
  9. ????????????IllegalAccessException,?InvocationTargetException??????{??
  10. ????????ResultBean?oResult?=?new?ResultBean();????
  11. ????????boolean?bRet?=?false;??????????String?sDescription?=?"";??
  12. ??????????//?get?full?text?DB?file?name?with?full?path??
  13. ????????String?sFullFileName?=?this.getFullTableFileName(oT);????
  14. ????????//?get?sRowdata??????????String?sRowData?=?this.convertBeantoStr(oT,?sFullFileName);??
  15. ??????????PrintWriter?oPWriter?=?null;??
  16. ????????try??????????{??
  17. ????????????//?get?writer??????????????oPWriter?=?fileProcess??
  18. ????????????????????.getAppendBufferedFilePrintWriter(sFullFileName);??????????????//?write?to?file??
  19. ????????????oPWriter.write(System.getProperty("line.separator")?+?sRowData);??????????????oPWriter.flush();??
  20. ??????????????//?set?return?value?as?success??
  21. ????????????bRet?=?true;??????????????sDescription?=?"the?insert?record?is?""?+?sRowData?+?"".?"??
  22. ????????????????????+?".?It?is?saved?in?""?+?sFullFileName??????????????????????+?""?successfully.";??
  23. ????????}??????????catch?(IOException?e)??
  24. ????????{??????????????e.printStackTrace();??
  25. ????????????throw?e;??????????}??
  26. ????????finally??????????{??
  27. ????????????//?close?the?writer??????????????if?(null?!=?oPWriter)??
  28. ????????????{??????????????????oPWriter.close();??
  29. ????????????}??????????}??
  30. ????????//?set?final?result.??????????oResult.setDescription(sDescription);??
  31. ????????oResult.setResult(bRet);????
  32. ????????return?oResult;??????}??

4. 先了解下如何将一条记录从文本数据库表文件中删除

java没有删除文本中某一行的接口,所以实现删除的算法就是,将文本内容全部读出来,将改行从缓存中删除,然后将处理后的缓存数据覆盖写入原文件. 缓存方式有两种一种全部存入内存适用于数据较少的时候,另一种是写入临时文件,适用于大数量时候.本demo全部读入内存了.

a. 获取对应DB文件的reader

b.然后一行一行的读取,一行一行的判断是否当前行就是要删除的行,如果不是则加入缓存的字符串中,否则丢弃

c.将处理后的缓存字符串写入对应的DB文件

?

[java] view plaincopy
  1. /**??????*?Author:?Jiangtao?He;?Email:?ross.jiangtao.he@gmail.com?
  2. ?????*?Description:???????*?1.delete?the?record?from?text?DB?file.??
  3. ?????*?2.the?arithmetic?is?read?all?the?contents?in??a?string?buffer?except???????*???the?deleting?record,?then?write?to?file?again.?
  4. ?????*?3.One?suggestion?for?huge?data,?develop?your?own?method?by?using?a??temporary?file??????*???as?a?buffered?
  5. ?????*?@param?sRowData:?the?record?which?will?be?deleted?from?the?file??????*?@param?sFullFileName:?DB?file?name?with?completing?path?
  6. ?????*?@return?bRet:?true?-?insert?success;?false?-?insert?failed??????*?@throws?IOException??
  7. ?????*/??????private?boolean?deleteRecordFromFile(String?sRowData,?String?sFullFileName)??
  8. ????????????throws?IOException??????{??
  9. ????????boolean?bRet?=?false;????
  10. ????????StringBuffer?sbFinalContent?=?new?StringBuffer();????
  11. ????????PrintWriter?oPWriter?=?null;??????????BufferedReader?oBRead?=?null;??
  12. ????????//?to?get?the?columns'?sequence??????????try??
  13. ????????{??????????????oBRead?=?fileProcess.getBufferedFileReader(sFullFileName);??
  14. ????????????String?sReadLine;??????????????String?sLastLIne?=?"sLastLIne";??
  15. ????????????while?(null?!=?(sReadLine?=?oBRead.readLine()))??????????????{??
  16. ????????????????sReadLine?=?sReadLine.trim();????
  17. ????????????????//?make?conjoined?duplicated?lines?to?one?line??????????????????//?to?avoid?too?many?empty?lines??
  18. ????????????????if?(sLastLIne.equals(sReadLine))??????????????????{??
  19. ????????????????????continue;??????????????????}??
  20. ????????????????//?delete?the?target?record??????????????????if?(sRowData.equals(sReadLine))??
  21. ????????????????{???????????????????//?set?result??
  22. ????????????????????bRet?=?true;??????????????????????????????????????????continue;??
  23. ????????????????}??????????????????//?cache?in?the?buffer??
  24. ????????????????sbFinalContent.append(sReadLine).append(??????????????????????????System.getProperty("line.separator"));??
  25. ????????????????//?set?last?line??????????????????sLastLIne?=?sReadLine;??
  26. ????????????}????
  27. ????????????//?get?writer??????????????oPWriter?=?fileProcess??
  28. ????????????????????.getBufferedFilePrintWriter(sFullFileName);????
  29. ????????????//?write?the?final?content?to?file??????????????oPWriter.write(sbFinalContent.toString());??
  30. ????????????oPWriter.flush();??????????}??
  31. ????????catch?(IOException?e)??????????{??
  32. ????????????//?print?e,?and?throw?it,?so?the?method?which?invoked?it?can?process??????????????//?it?freely.??
  33. ????????????e.printStackTrace();??????????????throw?e;??
  34. ????????}??????????finally??
  35. ????????{??????????????if?(null?!=?oBRead)??
  36. ????????????{??????????????????oBRead.close();??
  37. ????????????}??????????????//?close?the?writer??
  38. ????????????if?(null?!=?oPWriter)??????????????{??
  39. ????????????????oPWriter.close();??????????????}??
  40. ????????}??????????return?bRet;??
  41. ????}??

5. 有了上面的方法,我们就可以实现数据的删除功能了.

我们平时用的数据库可以使用主键或者其他字段作为条件来做删除, 这个在java里面就是多了一步字符串的分析操作.所以我没有实现这个功能, 在本demo中就是直接将整条记录作为判断条件来删除数据, 可以根据实际需要扩展本方法.

a.首先根据表的Bean对象获取文件名

b.然后将Bean对象转换为合格的表记录字符串

c.调用上面的方法将记录从文件中删除.

同样的,为了使所有的表Bean都可以通过这一个方法删除数据,将方法定义成了泛型方法.?

?

[java] view plaincopy
  1. ?/**??????*?Author:?Jiangtao?He;?Email:?ross.jiangtao.he@gmail.com?
  2. ?????*?Description:?Delete?one?record?from?text?DB??????*?@param?oT:?the?object?of?bean??
  3. ?????*?@return?oResult:???????*??????????ResultBean.result:?true?-?insert?success;?false?-?insert?failed?
  4. ?????*??????????ResultBean.description:?the?description?of?the?result;??????*?@throws?InvocationTargetException??
  5. ?????*?@throws?IllegalAccessException???????*?@throws?NoSuchMethodException??
  6. ?????*?@throws?IOException???????*?@throws?IllegalArgumentException??
  7. ?????*?@throws?SecurityException???????*/??
  8. ????public?<T>?ResultBean?delete(T?oT)?throws?SecurityException,??????????????IllegalArgumentException,?IOException,?NoSuchMethodException,??
  9. ????????????IllegalAccessException,?InvocationTargetException??????{??
  10. ????????ResultBean?oResult?=?new?ResultBean();????
  11. ????????boolean?bRet?=?false;??????????String?sDescription?=?"";??
  12. ??????????//?get?full?text?DB?file?name?with?full?path??
  13. ????????String?sFullFileName?=?this.getFullTableFileName(oT);????
  14. ??????????//?get?sRowdata??
  15. ????????String?sRowData?=?this.convertBeantoStr(oT,?sFullFileName);????
  16. ????????//?delete?from?file??????????bRet?=?this.deleteRecordFromFile(sRowData,?sFullFileName);??
  17. ??????????//?set?result?description??
  18. ????????if?(bRet)??????????{??
  19. ????????????sDescription?=?"The?deleted?record?is?""?+?sRowData?+?""?.?"??????????????????????+?"It?is?delete?from?""?+?sFullFileName??
  20. ????????????????????+?""?successfully.";??????????}??
  21. ????????else??????????{??
  22. ????????????sDescription?=?"The?deleting?record?""?+?sRowData??????????????????????+?""?is?not?there?in?the?file"?+?"?""?+?sFullFileName??
  23. ????????????????????+?"".";??????????}??
  24. ????????//?set?final?result.??????????oResult.setDescription(sDescription);??
  25. ????????oResult.setResult(bRet);????
  26. ????????return?oResult;??????}??
6.再看下如何更新文本数据库中的一条记录

更新记录算法和删除记录是一样的,只不过删除时丢弃该记录, 更新时更换该记录, 不再赘述.

?

a. 获取对应DB文件的reader

b.然后一行一行的读取,一行一行的判断是否当前行就是要删除的行,如果不是则加入缓存的字符串中,否则增更换为目标字符串

c.将处理后的缓存字符串写入对应的DB文件

?

[java] view plaincopy
  1. /**??????*?Author:?Jiangtao?He;?Email:?ross.jiangtao.he@gmail.com?
  2. ?????*?Description:???????*?1.update?the?record?to?text?DB?file.??
  3. ?????*?2.the?arithmetic?is?read?all?the?contents?in??a?string?buffer,?replace???????*???the?updating?record,?then?write?to?file?again.?
  4. ?????*?3.One?suggestion?for?huge?data,?develop?your?own?method?by?using?a??temporary?file??????*???as?a?buffered?
  5. ?????*?@param?sRowData:?the?record?which?will?be?deleted?from?the?file??????*?@param?sFullFileName:?DB?file?name?with?completing?path??
  6. ?????*?@param?sPrimaryKeyValue:?the?value?of?the?primary?key??????*?@return?bRet:?true?-?insert?success;?false?-?insert?failed?
  7. ?????*?@throws?IOException???????*/??
  8. ????private?boolean?updateRecordToFile(String?sRowData,??????????????String?sPrimaryKeyValue,?String?sFullFileName)?throws?IOException??
  9. ????{??????????boolean?bRet?=?false;??
  10. ??????????StringBuffer?sbFinalContent?=?new?StringBuffer();??
  11. ??????????PrintWriter?oPWriter?=?null;??
  12. ????????BufferedReader?oBRead?=?null;????
  13. ????????try??????????{??
  14. ????????????oBRead?=?fileProcess.getBufferedFileReader(sFullFileName);??????????????String?sReadLine;??
  15. ????????????String?sLastLIne?=?"sLastLIne";??????????????String[]?sColumnValues?=?null;??
  16. ????????????while?(null?!=?(sReadLine?=?oBRead.readLine()))??????????????{??
  17. ????????????????sReadLine?=?sReadLine.trim();????
  18. ????????????????//?make?conjoined?duplicated?lines?to?one?line??????????????????//?to?avoid?too?many?empty?lines??
  19. ????????????????if?(sLastLIne.equals(sReadLine))??????????????????{??
  20. ????????????????????continue;??????????????????}??
  21. ??????????????????//?handle?the?comments,?empty?line,?ColumnSeq?line??
  22. ????????????????if?(sReadLine.startsWith("#")?||?"".equals(sReadLine)??????????????????????????||?sReadLine.startsWith("ColumnSeq"))??
  23. ????????????????{??????????????????????//?cache?in?the?buffer??
  24. ????????????????????sbFinalContent.append(sReadLine).append(??????????????????????????????System.getProperty("line.separator"));??
  25. ????????????????????continue;??????????????????}??
  26. ??????????????????//?handle?changing?record??
  27. ????????????????sColumnValues?=?sReadLine.split("\\$_\\$");??????????????????if?(sPrimaryKeyValue.trim().equals(sColumnValues[0].trim()))??
  28. ????????????????{??????????????????????//?cache?in?the?buffer??
  29. ????????????????????sbFinalContent.append(sRowData).append(??????????????????????????????System.getProperty("line.separator"));??
  30. ????????????????????continue;??????????????????}??
  31. ??????????????????//?cache?normal?record?in?the?buffer??
  32. ????????????????sbFinalContent.append(sReadLine).append(??????????????????????????System.getProperty("line.separator"));??
  33. ??????????????????//?set?last?line??
  34. ????????????????sLastLIne?=?sReadLine;??????????????}??
  35. ??????????????//?get?writer??
  36. ????????????oPWriter?=?fileProcess.getBufferedFilePrintWriter(sFullFileName);????
  37. ????????????//?write?the?final?content?to?file??????????????oPWriter.write(sbFinalContent.toString());??
  38. ????????????oPWriter.flush();????
  39. ????????????//?set?result??????????????bRet?=?true;??
  40. ????????}??????????catch?(IOException?e)??
  41. ????????{??????????????//?print?e,?and?throw?it,?so?the?method?which?invoked?it?can?process??
  42. ????????????//?it?freely.??????????????e.printStackTrace();??
  43. ????????????throw?e;??????????}??
  44. ????????finally??????????{??
  45. ????????????if?(null?!=?oBRead)??????????????{??
  46. ????????????????oBRead.close();??????????????}??
  47. ????????????//?close?the?writer??????????????if?(null?!=?oPWriter)??
  48. ????????????{??????????????????oPWriter.close();??
  49. ????????????}??????????}??
  50. ????????return?bRet;??????}??

7. 通过上面的更新方法,就可以实现记录的更新功能了.

同样的对与更新方法没有实现根据列值判断来更新相关的记录, 只是实现了根据主键更新整列数据局, 可以根据需要重写/扩展该方法

a.首先根据Table Bean后去带路径的玩这个路径名

b.在将Table Bean转换成一个合格的数据记录字符串

c.调用上面的方法,根据主键将目标记录替换

同样的,为了使所有的表Bean都可以通过这一个方更新数据,将方法定义成了泛型方法.?

?

[java] view plaincopy
  1. /**??????*?Author:?Jiangtao?He;?Email:?ross.jiangtao.he@gmail.com?
  2. ?????*?Description:?update?one?record?from?text?DB??????*?@param?oT:?the?object?of?bean??
  3. ?????*?@param?sPrimaryKeyValue:?the?value?of?the?primary?key??????*?@return?oResult:??
  4. ?????*??????????ResultBean.result:?true?-?insert?success;?false?-?insert?failed??????*??????????ResultBean.description:?the?description?of?the?result;?
  5. ?????*?@throws?InvocationTargetException???????*?@throws?IllegalAccessException??
  6. ?????*?@throws?NoSuchMethodException???????*?@throws?IOException??
  7. ?????*?@throws?IllegalArgumentException???????*?@throws?SecurityException??
  8. ?????*/??????public?<T>?ResultBean?update(T?oT,?String?sPrimaryKeyValue)??
  9. ????????????throws?SecurityException,?IllegalArgumentException,?IOException,??????????????NoSuchMethodException,?IllegalAccessException,??
  10. ????????????InvocationTargetException??????{??
  11. ????????ResultBean?oResult?=?new?ResultBean();????
  12. ????????boolean?bRet?=?false;??????????String?sDescription?=?"";??
  13. ??????????//?get?full?text?DB?file?name?with?full?path??
  14. ????????String?sFullFileName?=?this.getFullTableFileName(oT);????
  15. ????????//?get?sRowdata??????????String?sRowData?=?this.convertBeantoStr(oT,?sFullFileName);??
  16. ??????????//?delete?from?file??
  17. ????????bRet?=?this.updateRecordToFile(sRowData,?sPrimaryKeyValue,??????????????????sFullFileName);??
  18. ??????????//?set?result?description??
  19. ????????if?(bRet)??????????{??
  20. ????????????sDescription?=?"The?updated?record?is?""?+?sRowData?+?"".?"??????????????????????+?"?It?is?update?to?""?+?sFullFileName??
  21. ????????????????????+?""?successfully.";??????????}??
  22. ????????else??????????{??
  23. ????????????sDescription?=?"The?updating?record?""?+?sRowData??????????????????????+?""?is?not?there?in?the?file"?+?"?""?+?sFullFileName??
  24. ????????????????????+?"".";??????????}??
  25. ????????//?set?final?result.??????????oResult.setDescription(sDescription);??
  26. ????????oResult.setResult(bRet);??????????return?oResult;??
  27. ????}??
8. 了解下如何根据列名获取Table Bean的get 方法

由于列名和Bean的Field名字是一样的,根据这儿特性,可以拼接出来对应的set方法的方法名. 详细步骤可以参考注释

同样的,为了使所有的表Bean都可以通过这一个方法获取set方法,将方法定义成了泛型方法.?

?

[java] view plaincopy
  1. /**??????*?Author:?Jiangtao?He;?Email:?ross.jiangtao.he@gmail.com?
  2. ?????*?Description:?Get?all?set?method?names.??????*?assume?that?all?the?field?names?of?bean?class?of?table?are?the?same?as?the?column?names?
  3. ?????*?@param?oT:?the?object?of?bean???????*?@param?sColumns:?the?columns?
  4. ?????*?@return?HashMap?<String,String>???????*???????????-?key:?column?name;???
  5. ?????*???????????-?value:?the?corresponding?set?method?name??????*/??
  6. ????private?<T>?HashMap<String,?String>?getSetMethods(String[]?sColumns,?T?oT)??????{??
  7. ????????HashMap<String,?String>?oHM?=?new?HashMap<String,?String>();??????????String?sMethodName?=?"";??
  8. ????????String?sFieldName?=?"";??????????for?(int?i?=?0;?i?<?sColumns.length;?i++)??
  9. ????????{??????????????//?initialize?the?method?name??
  10. ????????????sMethodName?=?"set";????
  11. ????????????//?get?the?get?method?name?of?the?current?column??????????????sFieldName?=?sColumns[i].trim();??
  12. ????????????if?(sFieldName.length()?>?1)??????????????{??
  13. ????????????????sMethodName?=?sMethodName??????????????????????????+?sFieldName.substring(0,?1).toUpperCase()??
  14. ????????????????????????+?sFieldName.substring(1);??????????????}??
  15. ????????????else??????????????{??
  16. ????????????????sMethodName?=?sMethodName?+?sFieldName.toUpperCase();??????????????}??
  17. ????????????oHM.put(sColumns[i],?sMethodName);??????????}??
  18. ????????return?oHM;??????}??

9. 有了上面的方法,我们也可以更加easy的实现数据的查询功能了.

为了免去分析字符串的麻烦,本demo只是先了查询所有数据的功能,可以根据需要扩展该方法.

这个方法设计是将所有数据读取出来放入Bean中,一条记录就是一个Bean对象,所以最终返回值是一个Bean对象的list

a.首先获取对应的带路径的完整文件名

b.获取对应数据库文件的reader

c.将数据一条一条的读出来,一条一条的处理. 跳过注释,空行,及标示列名和列顺序的行, 将其他有效的数据库记录进行处理

d.根据列名得出所有field的set方法

c.将数据库记录分割后,调用set方法赋给Bean对象

d.将赋值完后的Bean对象加入List, 如此循环处理所有记录.

同样的,为了使所有的表Bean都可以通过这一个方法获取对应的数据列表,将方法定义成了泛型方法.?

另外注意一点, 由于set方法是有输入参数的,所以使用反射机制构造或者执行方法的时候是需要指定这些参数类型或者参数的, 由于demo中的数据类型都是使用的String类型,所以是取巧了的, 如果需要支持其他类型,可以对此方法做修改,对类型做下分析.

?

[java] view plaincopy
  1. /**??????*?Author:?Jiangtao?He;?Email:?ross.jiangtao.he@gmail.com?
  2. ?????*?Description:?query?all?the?records?from?text?DB??????*?@param?oT:?the?object?of?bean??
  3. ?????*?@param?sPrimaryKeyValue:?the?value?of?the?primary?key??????*?@return?oTList:?the?object?list?of?the?bean?
  4. ?????*?@throws?InvocationTargetException???????*?@throws?IllegalAccessException??
  5. ?????*?@throws?IllegalArgumentException???????*?@throws?NoSuchMethodException??
  6. ?????*?@throws?SecurityException???????*?@throws?InstantiationException??
  7. ?????*?@throws?IOException???????*/??
  8. ????public?<T>?List<T>?queryAll(T?oT)?throws?IllegalArgumentException,??????????????IllegalAccessException,?InvocationTargetException,??
  9. ????????????SecurityException,?NoSuchMethodException,?InstantiationException,?IOException??????{??
  10. ????????List<T>?oTList?=?new?ArrayList<T>();????
  11. ????????//?get?full?text?DB?file?name?with?full?path??????????String?sFullFileName?=?this.getFullTableFileName(oT);??
  12. ??????????BufferedReader?oBRead?=?null;??
  13. ????????try??????????{??
  14. ????????????oBRead?=?fileProcess.getBufferedFileReader(sFullFileName);??????????????String?sReadLine;??
  15. ????????????String[]?sColumns?=?null;??????????????HashMap<String,?String>?oHM?=?null;??
  16. ????????????String[]?sColumnValues?=?null;??????????????int?iNumOfColumns;??
  17. ????????????Method?oMethod;??????????????while?(null?!=?(sReadLine?=?oBRead.readLine()))??
  18. ????????????{??????????????????sReadLine?=?sReadLine.trim();??
  19. ??????????????????//?skip?comments,?empty?line??
  20. ????????????????if?(sReadLine.startsWith("#")?||?"".equals(sReadLine))??????????????????{??
  21. ????????????????????continue;??????????????????}??
  22. ??????????????????//?get?set?method?names?of?the?bean??
  23. ????????????????if?(sReadLine.startsWith("ColumnSeq"))??????????????????{??
  24. ????????????????????sColumns?=?sReadLine.split(":")[1].split("\\$_\\$");??????????????????????oHM?=?this.getSetMethods(sColumns,?oT);??
  25. ????????????????????continue;??????????????????}??
  26. ??????????????????//?get?values?of?the?a?record??
  27. ????????????????sColumnValues?=?sReadLine.split("\\$_\\$");????
  28. ????????????????//?check?the?number?of?values?is?less?than?columns?or?not,?the??????????????????//?smaller?one?will?be?used?in?the?loop?to?avoid?out?of?array??
  29. ????????????????//?index?exception??????????????????iNumOfColumns?=?sColumnValues.length?>?sColumns.length???sColumns.length??
  30. ????????????????????????:?sColumnValues.length;??????????????????for?(int?i?=?0;?i?<?iNumOfColumns;?i++)??
  31. ????????????????{??????????????????????//?get?the?get?method??
  32. ????????????????????oMethod?=?oT.getClass().getMethod(oHM.get(sColumns[i]),String.class);??????????????????????//?execute?the?method?to?set?the?value?into?bean??
  33. ????????????????????oMethod.invoke(oT,?sColumnValues[i]);??????????????????}??
  34. ????????????????//add?the?bean?into?the?bean?list??????????????????oTList.add(oT);??
  35. ????????????????//assign?a?new?instance?to?the?bean??????????????????oT?=?(T)?oT.getClass().newInstance();??
  36. ????????????}??????????}??
  37. ????????catch?(IOException?e)??????????{??
  38. ????????????//?print?e,?and?throw?it,?so?the?method?which?invoked?it?can?process??????????????//?it?freely.??
  39. ????????????e.printStackTrace();??????????????throw?e;??
  40. ????????}??????????finally??
  41. ????????{??????????????if?(null?!=?oBRead)??
  42. ????????????{??????????????????oBRead.close();??
  43. ????????????}??????????}??
  44. ????????return?oTList;??????}??


?至此增删改查功能的思路算是实现了.


我们使用junit做下测试看下效果--我在4个测试方法上都打了断点, 分别看下实际效果(由于junit代码较长,我就不贴了,感兴趣的可以下载下来看):

增加一条记录到home和member表:

控制台:

?

[java] view plaincopy
  1. Insert?one?home?record?-?result:?true;?description:?the?insert?record?is?"Ross_1$_$Ross's?Home$_$252363693$_$ross.jiangtao.he@gmail.com$_$China?P.R.".?.?It?is?saved?in?"E:\myspace\MyJavaExpert?V1.0\db\T_Home.db"?successfully.??Insert?one?faminily?member?record?-?result:?true;?description:?the?insert?record?is?"Yan$_$Pery$_$Female$_$252363693$_$ross.jiangtao.he@gmail.com$_$null$_$Ross_1".?.?It?is?saved?in?"E:\myspace\MyJavaExpert?V1.0\db\T_FamilyMember.db"?successfully.??

数据库文件内容:

T_Home.db:

?

[java] view plaincopy
  1. #Column?Sequence??ColumnSeq:?id$_$name$_$phone$_$email$_$address??
  2. ??#Content?Start??
  3. Ross_1$_$Ross's?Home$_$252363693$_$ross.jiangtao.he@gmail.com$_$China?P.R.??
T_FamilyMember.db:

?

[java] view plaincopy
  1. #Column?Sequence??ColumnSeq:?id$_$name$_$gender$_$mobile$_$email$_$address$_$family_id??
  2. ??#content?start??
  3. Yan$_$Pery$_$Female$_$252363693$_$ross.jiangtao.he@gmail.com$_$null$_$Ross_1??

查询home和member表的记录:
控制台:

?

[java] view plaincopy
  1. Query?all?the?home?record(s)?from?file,?totally?get?:?1?record(s)??Query?all?the?family?member?record(s)?from?file,?totally?get?:?1?record(s)??

更新home和member表的记录(可以看多了"O(∩_∩)O~~"的列)控制台:

?

[java] view plaincopy
  1. Update?one?faminily?member?record?-?result:?true;?description:?The?updated?record?is?"Yan$_$Pery$_$Female$_$10086?O(∩_∩)O~~$_$ross.jiangtao.he@gmail.com$_$null$_$Ross_1".??It?is?update?to?"E:\myspace\MyJavaExpert?V1.0\db\T_FamilyMember.db"?successfully.??Update?one?home?record?-?result:?true;?description:?The?updated?record?is?"Ross_1$_$Pery's?Home?O(∩_∩)O~~$_$252363693$_$ross.jiangtao.he@gmail.com$_$China?P.R.".??It?is?update?to?"E:\myspace\MyJavaExpert?V1.0\db\T_Home.db"?successfully.??
T_Home.db:

?

[java] view plaincopy
  1. #Column?Sequence??ColumnSeq:?id$_$name$_$phone$_$email$_$address??
  2. #Content?Start??Ross_1$_$Pery's?Home?O(∩_∩)O~~$_$252363693$_$ross.jiangtao.he@gmail.com$_$China?P.R.??

T_FamilyMember.db:

[java] view plaincopy
  1. <pre?name="code"?class="java">#Column?Sequence??ColumnSeq:?id$_$name$_$gender$_$mobile$_$email$_$address$_$family_id??
  2. #content?start??Yan$_$Pery$_$Female$_$10086?O(∩_∩)O~~$_$ross.jiangtao.he@gmail.com$_$null$_$Ross_1??

删除home和member表的一条记录控制台:[java] view plaincopy
  1. Delete?one?faminily?member?record?-?result:?true;?description:?The?deleted?record?is?"Yan$_$Pery$_$Female$_$10086?O(∩_∩)O~~$_$ross.jiangtao.he@gmail.com$_$null$_$Ross_1"?.?It?is?delete?from?"E:\myspace\MyJavaExpert?V1.0\db\T_FamilyMember.db"?successfully.??Delete?one?home?record?-?result:?true;?description:?The?deleted?record?is?"Ross_1$_$Pery's?Home?O(∩_∩)O~~$_$252363693$_$ross.jiangtao.he@gmail.com$_$China?P.R."?.?It?is?delete?from?"E:\myspace\MyJavaExpert?V1.0\db\T_Home.db"?successfully.??
T_Home.db:[java] view plaincopy
  1. #Column?Sequence??ColumnSeq:?id$_$name$_$phone$_$email$_$address??
  2. #Content?Start??
T_FamilyMember.db:

?

[java] view plaincopy
  1. #Column?Sequence??ColumnSeq:?id$_$name$_$gender$_$mobile$_$email$_$address$_$family_id??
  2. #content?start??


?至此"文本数据库简单的实现思路"已经完成了.

热点排行