JAVA学习提高之----JAVA开源项目之操作csv文件

JAVA操作csv文件的开源项目很多,如想查可看下面链接
http://sourceforge.net/search/?type_of_search=soft&words=csv

看到网上有人认为不错的一个,地址是:
http://opencsv.sourceforge.net/

下载源码地址:http://sourceforge.net/project/showfiles.php?group_id=148905&package_id=164539
最新的是1.8版的,因为最近项目要用到CSV文件的读写,所以对有关内容进行学习,主要是对CSV文件分析器类的学习,下面只是发布出来的API,具体的类下载的资源里面有。

具体思路:因为csv file本身可以当作文件文件来操作,所以只需使用BufferedReader的readLine方法即可读取一行了。

  1. opencsv
  2. AnOpenSourceJavacsvlibraryundercommercial-friendlylicense...committedtochangingtheworld,onecommaatatime...
  3. Whatisopencsv?
  4. opencsvisaverysimplecsv(comma-separatedvalues)parserlibraryforJava.ItwasdevelopedbecauseallofcurrentcsvparsersI'vecomeacrossdon'thavecommercial-friendlylicenses.
  5. WherecanIgetit?
  6. SourceandbinariesareavailablefromSourceforge.
  7. Whatfeaturesdoesopencsvsupport?
  8. opencsvsupportsallthebasiccsv-typethingsyou'relikelytowanttodo:
  9. *Arbitrarynumbersofvaluesperline
  10. *Ignoringcommasinquotedelements
  11. *Handlingquotedentrieswithembeddedcarriagereturns(ieentriesthatspanmultiplelines)
  12. *Configurableseparatorandquotecharacters(orusesensibledefaults)
  13. *Readalltheentriesatonce,oruseanIteratorstylemodel
  14. *CreatingcsvfilesfromString[](ie.automaticescapingofembeddedquotechars)
  15. HowdoIreadandparseaCSVfile?
  16. IfyouwanttouseanIteratorstylepattern,youmightdosomethinglikethis:
  17. CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"));
  18. String[]nextLine;
  19. while((nextLine=reader.readNext())!=null){
  20. //nextLine[]isanarrayofvaluesfromtheline
  21. System.out.println(nextLine[0]+nextLine[1]+"etc...");
  22. }
  23. Or,ifyoumightjustwanttoslurpthewholelotintoaList,justcallreadAll()...
  24. CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"));
  25. ListmyEntries=reader.readAll();
  26. whichwillgiveyouaListofString[]thatyoucaniterateover.Ifallelsefails,checkouttheJavadoc.
  27. CanIusemyownseparatorsandquotecharacters?
  28. Yes.Thereareconstructorsthatcaterforsupplyingyourownseparatorandquotecharacters.Sayyou'reusingatabforyourseparator,youcandosomethinglikethis:
  29. CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"),'\t');
  30. Andifyousinglequotedyourescapedcharactersratherthandoublequotethem,youcanusethethreeargconstructor:
  31. CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"),'\t','\'');
  32. Youmayalsoskipthefirstfewlinesofthefileifyouknowthatthecontentdoesn'tstarttilllaterinthefile.So,forexample,youcanskipthefirsttwolinesbydoing:
  33. CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"),'\t','\'',2);
  34. CanIwritecsvfileswithopencsv?
  35. Yes.ThereisaCSVWriterinthesamepackagethatfollowsthesamesemanticsastheCSVReader.Forexample,towriteatabseparatedfile:
  36. CSVWriterwriter=newCSVWriter(newFileWriter("yourfile.csv"),'\t');
  37. //feedinyourarray(orconvertyourdatatoanarray)
  38. String[]entries="first#second#third".split("#");
  39. writer.writeNext(entries);
  40. writer.close();
  41. Ifyou'dprefertouseyourownquotecharacters,youmayusethethreeargversionoftheconstructor,whichtakesaquotecharacter(orfeelfreetopassinCSVWriter.NO_QUOTE_CHARACTER).
  42. Youcanalsocustomisethelineterminatorsusedinthegeneratedfile(whichishandywhenyou'reexportingfromyourLinuxwebapplicationtoWindowsclients).Thereisaconstructorargumentforthispurpose.
  43. CanIdumpoutSQLtablestoCSV?
  44. Yesyoucan.SeanSullivanaddedaneatfeaturetoCSVWritersoyoucanpasswriteAll()aResultSet.
  45. java.sql.ResultSetmyResultSet=....
  46. writer.writeAll(myResultSet,includeHeaders);
  47. IsthereawaytobindmyCSVfiletoalistofJavabeans?
  48. Yesthereis.KyleMilleraddedanewsetofclassestoallowyoutobindaCSVfiletoalistofJavaBeansbasedoncolumnname,columnposition,oracustommappingstrategy.Youcanfindthenewclassesintheau.com.bytecode.opencsv.beanpackage.Here'showyoucanmaptoajavabeanbasedonthefieldpositionsinyourCSVfile:
  49. ColumnPositionMappingStrategystrat=newColumnPositionMappingStrategy();
  50. strat.setType(YourOrderBean.class);
  51. String[]columns=newString[]{"name","orderNumber","id"};//thefieldstobinddoinyourJavaBean
  52. strat.setColumnMapping(columns);
  53. CsvToBeancsv=newCsvToBean();
  54. Listlist=csv.parse(strat,yourReader);
  55. Formoredetailedexamples,checkoutthetestcasesforeachoftheavailablemappingstrategiesunderthe/test/au/com/bytecode/opencsv/bean/.
  56. CanIuseopencsvinmycommercialapplications?
  57. Yes.opencsvisavailableunderacommercial-friendlyApache2.0license.Youarefreetoincludeitinyourcommericialapplicationswithoutanyfeeorcharge,andyouarefreetomodifyittosuityourcircumstances.Tofindoutmoredetailsofthelicense,readtheApache2.0licenseagreement.
  58. CanIgetthesource?Moreexamplecode?
  59. Yes.ThedownloadfromtheSourceForgepageincludesthefullsourceinthe/srcdirectory.It'sonefile,sogocrazy.Thereisalsoasampleaddressbookcsvreaderinthe/examplesdirectory.Andforextramarks,there'saJUnittestsuiteinthe/testdirectory.
  60. Whomaintainsopencsv?
  61. opencsvwasdevelopedinacoupleofhoursbyGlenSmith.Youcanreadhisblogformoreinfoandcontactdetails.
  62. Ifyou'vefoundabug,youcanreportitontheprojectpageatSourceforge.Pleasepostasamplefilethatdemonstratesyourissue.Forbonusmarks,postapatchtoo.:-)


对应的方法为:

  1. packageau.com.bytecode.opencsv;
  2. /**
  3. Copyright2005BytecodePtyLtd.
  4. LicensedundertheApacheLicense,Version2.0(the"License");
  5. youmaynotusethisfileexceptincompliancewiththeLicense.
  6. YoumayobtainacopyoftheLicenseat
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  9. distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  10. WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  11. SeetheLicenseforthespecificlanguagegoverningpermissionsand
  12. limitationsundertheLicense.
  13. */
  14. importjava.io.BufferedReader;
  15. importjava.io.IOException;
  16. importjava.io.Reader;
  17. importjava.util.ArrayList;
  18. importjava.util.List;
  19. /**
  20. *AverysimpleCSVreaderreleasedunderacommercial-friendlylicense.
  21. *
  22. *@authorGlenSmith
  23. *
  24. */
  25. publicclassCSVReader{
  26. privateBufferedReaderbr;
  27. privatebooleanhasNext=true;
  28. privatecharseparator;
  29. privatecharquotechar;
  30. privateintskipLines;
  31. privatebooleanlinesSkiped;
  32. /**Thedefaultseparatortouseifnoneissuppliedtotheconstructor.*/
  33. publicstaticfinalcharDEFAULT_SEPARATOR=',';
  34. /**
  35. *Thedefaultquotecharactertouseifnoneissuppliedtothe
  36. *constructor.
  37. */
  38. publicstaticfinalcharDEFAULT_QUOTE_CHARACTER='"';
  39. /**
  40. *Thedefaultlinetostartreading.
  41. */
  42. publicstaticfinalintDEFAULT_SKIP_LINES=0;
  43. /**
  44. *ConstructsCSVReaderusingacommafortheseparator.
  45. *
  46. *@paramreader
  47. *thereadertoanunderlyingCSVsource.
  48. */
  49. publicCSVReader(Readerreader){
  50. this(reader,DEFAULT_SEPARATOR);
  51. }
  52. /**
  53. *ConstructsCSVReaderwithsuppliedseparator.
  54. *
  55. *@paramreader
  56. *thereadertoanunderlyingCSVsource.
  57. *@paramseparator
  58. *thedelimitertouseforseparatingentries.
  59. */
  60. publicCSVReader(Readerreader,charseparator){
  61. this(reader,separator,DEFAULT_QUOTE_CHARACTER);
  62. }
  63. /**
  64. *ConstructsCSVReaderwithsuppliedseparatorandquotechar.
  65. *
  66. *@paramreader
  67. *thereadertoanunderlyingCSVsource.
  68. *@paramseparator
  69. *thedelimitertouseforseparatingentries
  70. *@paramquotechar
  71. *thecharactertouseforquotedelements
  72. */
  73. publicCSVReader(Readerreader,charseparator,charquotechar){
  74. this(reader,separator,quotechar,DEFAULT_SKIP_LINES);
  75. }
  76. /**
  77. *ConstructsCSVReaderwithsuppliedseparatorandquotechar.
  78. *
  79. *@paramreader
  80. *thereadertoanunderlyingCSVsource.
  81. *@paramseparator
  82. *thedelimitertouseforseparatingentries
  83. *@paramquotechar
  84. *thecharactertouseforquotedelements
  85. *@paramline
  86. *thelinenumbertoskipforstartreading
  87. */
  88. publicCSVReader(Readerreader,charseparator,charquotechar,intline){
  89. this.br=newBufferedReader(reader);
  90. this.separator=separator;
  91. this.quotechar=quotechar;
  92. this.skipLines=line;
  93. }
  94. /**
  95. *ReadstheentirefileintoaListwitheachelementbeingaString[]of
  96. *tokens.
  97. *
  98. *@returnaListofString[],witheachString[]representingalineofthe
  99. *file.
  100. *
  101. *@throwsIOException
  102. *ifbadthingshappenduringtheread
  103. */
  104. publicListreadAll()throwsIOException{
  105. ListallElements=newArrayList();
  106. while(hasNext){
  107. String[]nextLineAsTokens=readNext();
  108. if(nextLineAsTokens!=null)
  109. allElements.add(nextLineAsTokens);
  110. }
  111. returnallElements;
  112. }
  113. /**
  114. *Readsthenextlinefromthebufferandconvertstoastringarray.
  115. *
  116. *@returnastringarraywitheachcomma-separatedelementasaseparate
  117. *entry.
  118. *
  119. *@throwsIOException
  120. *ifbadthingshappenduringtheread
  121. */
  122. publicString[]readNext()throwsIOException{
  123. StringnextLine=getNextLine();
  124. returnhasNext?parseLine(nextLine):null;
  125. }
  126. /**
  127. *Readsthenextlinefromthefile.
  128. *
  129. *@returnthenextlinefromthefilewithouttrailingnewline
  130. *@throwsIOException
  131. *ifbadthingshappenduringtheread
  132. */
  133. privateStringgetNextLine()throwsIOException{
  134. if(!this.linesSkiped){
  135. for(inti=0;i<skipLines;i++){
  136. br.readLine();
  137. }
  138. this.linesSkiped=true;
  139. }
  140. StringnextLine=br.readLine();
  141. if(nextLine==null){
  142. hasNext=false;
  143. }
  144. returnhasNext?nextLine:null;
  145. }
  146. /**
  147. *ParsesanincomingStringandreturnsanarrayofelements.
  148. *
  149. *@paramnextLine
  150. *thestringtoparse
  151. *@returnthecomma-tokenizedlistofelements,ornullifnextLineisnull
  152. *@throwsIOExceptionifbadthingshappenduringtheread
  153. */
  154. privateString[]parseLine(StringnextLine)throwsIOException{
  155. if(nextLine==null){
  156. returnnull;
  157. }
  158. ListtokensOnThisLine=newArrayList();
  159. StringBuffersb=newStringBuffer();
  160. booleaninQuotes=false;
  161. do{
  162. if(inQuotes){
  163. //continuingaquotedsection,reappendnewline
  164. sb.append("\n");
  165. nextLine=getNextLine();
  166. if(nextLine==null)
  167. break;
  168. }
  169. for(inti=0;i<nextLine.length();i++){
  170. charc=nextLine.charAt(i);
  171. if(c==quotechar){
  172. //thisgetscomplex...thequotemayendaquotedblock,orescapeanotherquote.
  173. //doa1-charlookahead:
  174. if(inQuotes//weareinquotes,thereforetherecanbeescapedquotesinhere.
  175. &&nextLine.length()>(i+1)//thereisindeedanothercharactertocheck.
  176. &&nextLine.charAt(i+1)==quotechar){//..andthatchar.isaquotealso.
  177. //wehavetwoquotecharsinarow==onequotechar,soconsumethembothand
  178. //putoneonthetoken.wedo*not*exitthequotedtext.
  179. sb.append(nextLine.charAt(i+1));
  180. i++;
  181. }else{
  182. inQuotes=!inQuotes;
  183. //thetrickycaseofanembeddedquoteinthemiddle:a,bc"d"ef,g
  184. if(i>2//notonthebeginingoftheline
  185. &&nextLine.charAt(i-1)!=this.separator//notatthebeginingofanescapesequence
  186. &&nextLine.length()>(i+1)&&
  187. nextLine.charAt(i+1)!=this.separator//notattheendofanescapesequence
  188. ){
  189. sb.append(c);
  190. }
  191. }
  192. }elseif(c==separator&&!inQuotes){
  193. tokensOnThisLine.add(sb.toString());
  194. sb=newStringBuffer();//startworkonnexttoken
  195. }else{
  196. sb.append(c);
  197. }
  198. }
  199. }while(inQuotes);
  200. tokensOnThisLine.add(sb.toString());
  201. return(String[])tokensOnThisLine.toArray(newString[0]);
  202. }
  203. /**
  204. *Closestheunderlyingreader.
  205. *
  206. *@throwsIOExceptioniftheclosefails
  207. */
  208. publicvoidclose()throwsIOException{
  209. br.close();
  210. }
  211. }
  1. packageau.com.bytecode.opencsv;
  2. /**
  3. Copyright2005BytecodePtyLtd.
  4. LicensedundertheApacheLicense,Version2.0(the"License");
  5. youmaynotusethisfileexceptincompliancewiththeLicense.
  6. YoumayobtainacopyoftheLicenseat
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  9. distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  10. WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  11. SeetheLicenseforthespecificlanguagegoverningpermissionsand
  12. limitationsundertheLicense.
  13. */
  14. importjava.io.IOException;
  15. importjava.io.PrintWriter;
  16. importjava.io.Reader;
  17. importjava.io.Writer;
  18. importjava.math.BigDecimal;
  19. importjava.sql.Clob;
  20. importjava.sql.ResultSet;
  21. importjava.sql.ResultSetMetaData;
  22. importjava.sql.SQLException;
  23. importjava.sql.Time;
  24. importjava.sql.Timestamp;
  25. importjava.sql.Types;
  26. importjava.text.SimpleDateFormat;
  27. importjava.util.Iterator;
  28. importjava.util.List;
  29. /**
  30. *AverysimpleCSVwriterreleasedunderacommercial-friendlylicense.
  31. *
  32. *@authorGlenSmith
  33. *
  34. */
  35. publicclassCSVWriter{
  36. privateWriterrawWriter;
  37. privatePrintWriterpw;
  38. privatecharseparator;
  39. privatecharquotechar;
  40. privatecharescapechar;
  41. privateStringlineEnd;
  42. /**Thecharacterusedforescapingquotes.*/
  43. publicstaticfinalcharDEFAULT_ESCAPE_CHARACTER='"';
  44. /**Thedefaultseparatortouseifnoneissuppliedtotheconstructor.*/
  45. publicstaticfinalcharDEFAULT_SEPARATOR=',';
  46. /**
  47. *Thedefaultquotecharactertouseifnoneissuppliedtothe
  48. *constructor.
  49. */
  50. publicstaticfinalcharDEFAULT_QUOTE_CHARACTER='"';
  51. /**Thequoteconstanttousewhenyouwishtosuppressallquoting.*/
  52. publicstaticfinalcharNO_QUOTE_CHARACTER='\u0000';
  53. /**Theescapeconstanttousewhenyouwishtosuppressallescaping.*/
  54. publicstaticfinalcharNO_ESCAPE_CHARACTER='\u0000';
  55. /**Defaultlineterminatorusesplatformencoding.*/
  56. publicstaticfinalStringDEFAULT_LINE_END="\n";
  57. privatestaticfinalSimpleDateFormat
  58. TIMESTAMP_FORMATTER=
  59. newSimpleDateFormat("dd-MMM-yyyyHH:mm:ss");
  60. privatestaticfinalSimpleDateFormat
  61. DATE_FORMATTER=
  62. newSimpleDateFormat("dd-MMM-yyyy");
  63. /**
  64. *ConstructsCSVWriterusingacommafortheseparator.
  65. *
  66. *@paramwriter
  67. *thewritertoanunderlyingCSVsource.
  68. */
  69. publicCSVWriter(Writerwriter){
  70. this(writer,DEFAULT_SEPARATOR);
  71. }
  72. /**
  73. *ConstructsCSVWriterwithsuppliedseparator.
  74. *
  75. *@paramwriter
  76. *thewritertoanunderlyingCSVsource.
  77. *@paramseparator
  78. *thedelimitertouseforseparatingentries.
  79. */
  80. publicCSVWriter(Writerwriter,charseparator){
  81. this(writer,separator,DEFAULT_QUOTE_CHARACTER);
  82. }
  83. /**
  84. *ConstructsCSVWriterwithsuppliedseparatorandquotechar.
  85. *
  86. *@paramwriter
  87. *thewritertoanunderlyingCSVsource.
  88. *@paramseparator
  89. *thedelimitertouseforseparatingentries
  90. *@paramquotechar
  91. *thecharactertouseforquotedelements
  92. */
  93. publicCSVWriter(Writerwriter,charseparator,charquotechar){
  94. this(writer,separator,quotechar,DEFAULT_ESCAPE_CHARACTER);
  95. }
  96. /**
  97. *ConstructsCSVWriterwithsuppliedseparatorandquotechar.
  98. *
  99. *@paramwriter
  100. *thewritertoanunderlyingCSVsource.
  101. *@paramseparator
  102. *thedelimitertouseforseparatingentries
  103. *@paramquotechar
  104. *thecharactertouseforquotedelements
  105. *@paramescapechar
  106. *thecharactertouseforescapingquotecharsorescapechars
  107. */
  108. publicCSVWriter(Writerwriter,charseparator,charquotechar,charescapechar){
  109. this(writer,separator,quotechar,escapechar,DEFAULT_LINE_END);
  110. }
  111. /**
  112. *ConstructsCSVWriterwithsuppliedseparatorandquotechar.
  113. *
  114. *@paramwriter
  115. *thewritertoanunderlyingCSVsource.
  116. *@paramseparator
  117. *thedelimitertouseforseparatingentries
  118. *@paramquotechar
  119. *thecharactertouseforquotedelements
  120. *@paramlineEnd
  121. *thelinefeedterminatortouse
  122. */
  123. publicCSVWriter(Writerwriter,charseparator,charquotechar,StringlineEnd){
  124. this(writer,separator,quotechar,DEFAULT_ESCAPE_CHARACTER,lineEnd);
  125. }
  126. /**
  127. *ConstructsCSVWriterwithsuppliedseparator,quotechar,escapecharandlineending.
  128. *
  129. *@paramwriter
  130. *thewritertoanunderlyingCSVsource.
  131. *@paramseparator
  132. *thedelimitertouseforseparatingentries
  133. *@paramquotechar
  134. *thecharactertouseforquotedelements
  135. *@paramescapechar
  136. *thecharactertouseforescapingquotecharsorescapechars
  137. *@paramlineEnd
  138. *thelinefeedterminatortouse
  139. */
  140. publicCSVWriter(Writerwriter,charseparator,charquotechar,charescapechar,StringlineEnd){
  141. this.rawWriter=writer;
  142. this.pw=newPrintWriter(writer);
  143. this.separator=separator;
  144. this.quotechar=quotechar;
  145. this.escapechar=escapechar;
  146. this.lineEnd=lineEnd;
  147. }
  148. /**
  149. *WritestheentirelisttoaCSVfile.Thelistisassumedtobea
  150. *String[]
  151. *
  152. *@paramallLines
  153. *aListofString[],witheachString[]representingalineof
  154. *thefile.
  155. */
  156. publicvoidwriteAll(ListallLines){
  157. for(Iteratoriter=allLines.iterator();iter.hasNext();){
  158. String[]nextLine=(String[])iter.next();
  159. writeNext(nextLine);
  160. }
  161. }
  162. protectedvoidwriteColumnNames(ResultSetMetaDatametadata)
  163. throwsSQLException{
  164. intcolumnCount=metadata.getColumnCount();
  165. String[]nextLine=newString[columnCount];
  166. for(inti=0;i<columnCount;i++){
  167. nextLine[i]=metadata.getColumnName(i+1);
  168. }
  169. writeNext(nextLine);
  170. }
  171. /**
  172. *WritestheentireResultSettoaCSVfile.
  173. *
  174. *ThecallerisresponsibleforclosingtheResultSet.
  175. *
  176. *@paramrstherecordsettowrite
  177. *@paramincludeColumnNamestrueifyouwantcolumnnamesintheoutput,falseotherwise
  178. *
  179. */
  180. publicvoidwriteAll(java.sql.ResultSetrs,booleanincludeColumnNames)throwsSQLException,IOException{
  181. ResultSetMetaDatametadata=rs.getMetaData();
  182. if(includeColumnNames){
  183. writeColumnNames(metadata);
  184. }
  185. intcolumnCount=metadata.getColumnCount();
  186. while(rs.next())
  187. {
  188. String[]nextLine=newString[columnCount];
  189. for(inti=0;i<columnCount;i++){
  190. nextLine[i]=getColumnValue(rs,metadata.getColumnType(i+1),i+1);
  191. }
  192. writeNext(nextLine);
  193. }
  194. }
  195. privatestaticStringgetColumnValue(ResultSetrs,intcolType,intcolIndex)
  196. throwsSQLException,IOException{
  197. Stringvalue="";
  198. switch(colType)
  199. {
  200. caseTypes.BIT:
  201. Objectbit=rs.getObject(colIndex);
  202. if(bit!=null){
  203. value=String.valueOf(bit);
  204. }
  205. break;
  206. caseTypes.BOOLEAN:
  207. booleanb=rs.getBoolean(colIndex);
  208. if(!rs.wasNull()){
  209. value=Boolean.valueOf(b).toString();
  210. }
  211. break;
  212. caseTypes.CLOB:
  213. Clobc=rs.getClob(colIndex);
  214. if(c!=null){
  215. value=read(c);
  216. }
  217. break;
  218. caseTypes.BIGINT:
  219. caseTypes.DECIMAL:
  220. caseTypes.DOUBLE:
  221. caseTypes.FLOAT:
  222. caseTypes.REAL:
  223. caseTypes.NUMERIC:
  224. BigDecimalbd=rs.getBigDecimal(colIndex);
  225. if(bd!=null){
  226. value=""+bd.doubleValue();
  227. }
  228. break;
  229. caseTypes.INTEGER:
  230. caseTypes.TINYINT:
  231. caseTypes.SMALLINT:
  232. intintValue=rs.getInt(colIndex);
  233. if(!rs.wasNull()){
  234. value=""+intValue;
  235. }
  236. break;
  237. caseTypes.JAVA_OBJECT:
  238. Objectobj=rs.getObject(colIndex);
  239. if(obj!=null){
  240. value=String.valueOf(obj);
  241. }
  242. break;
  243. caseTypes.DATE:
  244. java.sql.Datedate=rs.getDate(colIndex);
  245. if(date!=null){
  246. value=DATE_FORMATTER.format(date);;
  247. }
  248. break;
  249. caseTypes.TIME:
  250. Timet=rs.getTime(colIndex);
  251. if(t!=null){
  252. value=t.toString();
  253. }
  254. break;
  255. caseTypes.TIMESTAMP:
  256. Timestamptstamp=rs.getTimestamp(colIndex);
  257. if(tstamp!=null){
  258. value=TIMESTAMP_FORMATTER.format(tstamp);
  259. }
  260. break;
  261. caseTypes.LONGVARCHAR:
  262. caseTypes.VARCHAR:
  263. caseTypes.CHAR:
  264. value=rs.getString(colIndex);
  265. break;
  266. default:
  267. value="";
  268. }
  269. if(value==null)
  270. {
  271. value="";
  272. }
  273. returnvalue;
  274. }
  275. privatestaticStringread(Clobc)throwsSQLException,IOException
  276. {
  277. StringBuffersb=newStringBuffer((int)c.length());
  278. Readerr=c.getCharacterStream();
  279. char[]cbuf=newchar[2048];
  280. intn=0;
  281. while((n=r.read(cbuf,0,cbuf.length))!=-1){
  282. if(n>0){
  283. sb.append(cbuf,0,n);
  284. }
  285. }
  286. returnsb.toString();
  287. }
  288. /**
  289. *Writesthenextlinetothefile.
  290. *
  291. *@paramnextLine
  292. *astringarraywitheachcomma-separatedelementasaseparate
  293. *entry.
  294. */
  295. publicvoidwriteNext(String[]nextLine){
  296. if(nextLine==null)
  297. return;
  298. StringBuffersb=newStringBuffer();
  299. for(inti=0;i<nextLine.length;i++){
  300. if(i!=0){
  301. sb.append(separator);
  302. }
  303. StringnextElement=nextLine[i];
  304. if(nextElement==null)
  305. continue;
  306. if(quotechar!=NO_QUOTE_CHARACTER)
  307. sb.append(quotechar);
  308. for(intj=0;j<nextElement.length();j++){
  309. charnextChar=nextElement.charAt(j);
  310. if(escapechar!=NO_ESCAPE_CHARACTER&&nextChar==quotechar){
  311. sb.append(escapechar).append(nextChar);
  312. }elseif(escapechar!=NO_ESCAPE_CHARACTER&&nextChar==escapechar){
  313. sb.append(escapechar).append(nextChar);
  314. }else{
  315. sb.append(nextChar);
  316. }
  317. }
  318. if(quotechar!=NO_QUOTE_CHARACTER)
  319. sb.append(quotechar);
  320. }
  321. sb.append(lineEnd);
  322. pw.write(sb.toString());
  323. }
  324. /**
  325. *Flushunderlyingstreamtowriter.
  326. *
  327. *@throwsIOExceptionifbadthingshappen
  328. */
  329. publicvoidflush()throwsIOException{
  330. pw.flush();
  331. }
  332. /**
  333. *Closetheunderlyingstreamwriterflushinganybufferedcontent.
  334. *
  335. *@throwsIOExceptionifbadthingshappen
  336. *
  337. */
  338. publicvoidclose()throwsIOException{
  339. pw.flush();
  340. pw.close();
  341. rawWriter.close();
  342. }
  343. }



以下是达人对此API做的测试:
http://blog.csdn.net/lord_is_layuping/archive/2008/02/14/2095766.aspx

我也做了测试,实际上直接调用API中的方法即可,不过还是应该看懂源码,感觉写的不错,对提高水平有很大的帮助,以后在开源项目方面要多看看。。。

你可能感兴趣的:(java,sql,C++,c,C#)