- 浏览: 1240261 次
- 性别:
- 来自: 深圳
文章分类
- 全部博客 (718)
- HTML (13)
- JS基础 (23)
- JS应用 (40)
- AJAX (6)
- JSP相关 (12)
- JAVA基础 (52)
- JAVA应用 (74)
- APPLET (11)
- SWING\RCP (2)
- JAVA反射 (6)
- 设计模式 (26)
- 数据库设计 (20)
- Struts (35)
- Struts2 (12)
- Spring (22)
- Hibernate (45)
- Ibatis (18)
- mybatis (3)
- SSH (8)
- UML (5)
- WebService (3)
- XML (16)
- Log4j (7)
- WEB容器 (26)
- 数据结构 (36)
- Linux (34)
- Ruby on Rails (1)
- 其它技术 (27)
- IDE配置 (15)
- 项目实战 (2)
- Oracle (69)
- JAVA报表 (7)
- Android学习 (2)
- 博客链接 (1)
- 网络基础 (1)
- WEB集群 (1)
- .Net开发 (11)
- PB (4)
- 系统构建 (15)
最新评论
-
jnjeC:
牛逼啊哥们,讲得太好了
Maven仓库理解、如何引入本地包、Maven多种方式打可执行jar包 -
九尾狐的yi巴:
很好 感谢!
Itext中文处理(更新版) -
luweifeng1983:
有用的,重启一下嘛。
设置eclipse外部修改文件后自动刷新 -
Master-Gao:
设置了也不管用,怎么破呢?
设置eclipse外部修改文件后自动刷新 -
aigo_h:
锋子还有时间写博客,还是很闲哈!
Add directory entries问题
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方法即可读取一行了。
- opencsv
- AnOpenSourceJavacsvlibraryundercommercial-friendlylicense...committedtochangingtheworld,onecommaatatime...
- Whatisopencsv?
- opencsvisaverysimplecsv(comma-separatedvalues)parserlibraryforJava.ItwasdevelopedbecauseallofcurrentcsvparsersI'vecomeacrossdon'thavecommercial-friendlylicenses.
- WherecanIgetit?
- SourceandbinariesareavailablefromSourceforge.
- Whatfeaturesdoesopencsvsupport?
- opencsvsupportsallthebasiccsv-typethingsyou'relikelytowanttodo:
- *Arbitrarynumbersofvaluesperline
- *Ignoringcommasinquotedelements
- *Handlingquotedentrieswithembeddedcarriagereturns(ieentriesthatspanmultiplelines)
- *Configurableseparatorandquotecharacters(orusesensibledefaults)
- *Readalltheentriesatonce,oruseanIteratorstylemodel
- *CreatingcsvfilesfromString[](ie.automaticescapingofembeddedquotechars)
- HowdoIreadandparseaCSVfile?
- IfyouwanttouseanIteratorstylepattern,youmightdosomethinglikethis:
- CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"));
- String[]nextLine;
- while((nextLine=reader.readNext())!=null){
- //nextLine[]isanarrayofvaluesfromtheline
- System.out.println(nextLine[0]+nextLine[1]+"etc...");
- }
- Or,ifyoumightjustwanttoslurpthewholelotintoaList,justcallreadAll()...
- CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"));
- ListmyEntries=reader.readAll();
- whichwillgiveyouaListofString[]thatyoucaniterateover.Ifallelsefails,checkouttheJavadoc.
- CanIusemyownseparatorsandquotecharacters?
- Yes.Thereareconstructorsthatcaterforsupplyingyourownseparatorandquotecharacters.Sayyou'reusingatabforyourseparator,youcandosomethinglikethis:
- CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"),'\t');
- Andifyousinglequotedyourescapedcharactersratherthandoublequotethem,youcanusethethreeargconstructor:
- CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"),'\t','\'');
- Youmayalsoskipthefirstfewlinesofthefileifyouknowthatthecontentdoesn'tstarttilllaterinthefile.So,forexample,youcanskipthefirsttwolinesbydoing:
- CSVReaderreader=newCSVReader(newFileReader("yourfile.csv"),'\t','\'',2);
- CanIwritecsvfileswithopencsv?
- Yes.ThereisaCSVWriterinthesamepackagethatfollowsthesamesemanticsastheCSVReader.Forexample,towriteatabseparatedfile:
- CSVWriterwriter=newCSVWriter(newFileWriter("yourfile.csv"),'\t');
- //feedinyourarray(orconvertyourdatatoanarray)
- String[]entries="first#second#third".split("#");
- writer.writeNext(entries);
- writer.close();
- Ifyou'dprefertouseyourownquotecharacters,youmayusethethreeargversionoftheconstructor,whichtakesaquotecharacter(orfeelfreetopassinCSVWriter.NO_QUOTE_CHARACTER).
- Youcanalsocustomisethelineterminatorsusedinthegeneratedfile(whichishandywhenyou'reexportingfromyourLinuxwebapplicationtoWindowsclients).Thereisaconstructorargumentforthispurpose.
- CanIdumpoutSQLtablestoCSV?
- Yesyoucan.SeanSullivanaddedaneatfeaturetoCSVWritersoyoucanpasswriteAll()aResultSet.
- java.sql.ResultSetmyResultSet=....
- writer.writeAll(myResultSet,includeHeaders);
- IsthereawaytobindmyCSVfiletoalistofJavabeans?
- Yesthereis.KyleMilleraddedanewsetofclassestoallowyoutobindaCSVfiletoalistofJavaBeansbasedoncolumnname,columnposition,oracustommappingstrategy.Youcanfindthenewclassesintheau.com.bytecode.opencsv.beanpackage.Here'showyoucanmaptoajavabeanbasedonthefieldpositionsinyourCSVfile:
- ColumnPositionMappingStrategystrat=newColumnPositionMappingStrategy();
- strat.setType(YourOrderBean.class);
- String[]columns=newString[]{"name","orderNumber","id"};//thefieldstobinddoinyourJavaBean
- strat.setColumnMapping(columns);
- CsvToBeancsv=newCsvToBean();
- Listlist=csv.parse(strat,yourReader);
- Formoredetailedexamples,checkoutthetestcasesforeachoftheavailablemappingstrategiesunderthe/test/au/com/bytecode/opencsv/bean/.
- CanIuseopencsvinmycommercialapplications?
- Yes.opencsvisavailableunderacommercial-friendlyApache2.0license.Youarefreetoincludeitinyourcommericialapplicationswithoutanyfeeorcharge,andyouarefreetomodifyittosuityourcircumstances.Tofindoutmoredetailsofthelicense,readtheApache2.0licenseagreement.
- CanIgetthesource?Moreexamplecode?
- Yes.ThedownloadfromtheSourceForgepageincludesthefullsourceinthe/srcdirectory.It'sonefile,sogocrazy.Thereisalsoasampleaddressbookcsvreaderinthe/examplesdirectory.Andforextramarks,there'saJUnittestsuiteinthe/testdirectory.
- Whomaintainsopencsv?
- opencsvwasdevelopedinacoupleofhoursbyGlenSmith.Youcanreadhisblogformoreinfoandcontactdetails.
- Ifyou'vefoundabug,youcanreportitontheprojectpageatSourceforge.Pleasepostasamplefilethatdemonstratesyourissue.Forbonusmarks,postapatchtoo.:-)
对应的方法为:
- packageau.com.bytecode.opencsv;
- /**
- Copyright2005BytecodePtyLtd.
- LicensedundertheApacheLicense,Version2.0(the"License");
- youmaynotusethisfileexceptincompliancewiththeLicense.
- YoumayobtainacopyoftheLicenseat
- http://www.apache.org/licenses/LICENSE-2.0
- Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- SeetheLicenseforthespecificlanguagegoverningpermissionsand
- limitationsundertheLicense.
- */
- importjava.io.BufferedReader;
- importjava.io.IOException;
- importjava.io.Reader;
- importjava.util.ArrayList;
- importjava.util.List;
- /**
- *AverysimpleCSVreaderreleasedunderacommercial-friendlylicense.
- *
- *@authorGlenSmith
- *
- */
- publicclassCSVReader{
- privateBufferedReaderbr;
- privatebooleanhasNext=true;
- privatecharseparator;
- privatecharquotechar;
- privateintskipLines;
- privatebooleanlinesSkiped;
- /**Thedefaultseparatortouseifnoneissuppliedtotheconstructor.*/
- publicstaticfinalcharDEFAULT_SEPARATOR=',';
- /**
- *Thedefaultquotecharactertouseifnoneissuppliedtothe
- *constructor.
- */
- publicstaticfinalcharDEFAULT_QUOTE_CHARACTER='"';
- /**
- *Thedefaultlinetostartreading.
- */
- publicstaticfinalintDEFAULT_SKIP_LINES=0;
- /**
- *ConstructsCSVReaderusingacommafortheseparator.
- *
- *@paramreader
- *thereadertoanunderlyingCSVsource.
- */
- publicCSVReader(Readerreader){
- this(reader,DEFAULT_SEPARATOR);
- }
- /**
- *ConstructsCSVReaderwithsuppliedseparator.
- *
- *@paramreader
- *thereadertoanunderlyingCSVsource.
- *@paramseparator
- *thedelimitertouseforseparatingentries.
- */
- publicCSVReader(Readerreader,charseparator){
- this(reader,separator,DEFAULT_QUOTE_CHARACTER);
- }
- /**
- *ConstructsCSVReaderwithsuppliedseparatorandquotechar.
- *
- *@paramreader
- *thereadertoanunderlyingCSVsource.
- *@paramseparator
- *thedelimitertouseforseparatingentries
- *@paramquotechar
- *thecharactertouseforquotedelements
- */
- publicCSVReader(Readerreader,charseparator,charquotechar){
- this(reader,separator,quotechar,DEFAULT_SKIP_LINES);
- }
- /**
- *ConstructsCSVReaderwithsuppliedseparatorandquotechar.
- *
- *@paramreader
- *thereadertoanunderlyingCSVsource.
- *@paramseparator
- *thedelimitertouseforseparatingentries
- *@paramquotechar
- *thecharactertouseforquotedelements
- *@paramline
- *thelinenumbertoskipforstartreading
- */
- publicCSVReader(Readerreader,charseparator,charquotechar,intline){
- this.br=newBufferedReader(reader);
- this.separator=separator;
- this.quotechar=quotechar;
- this.skipLines=line;
- }
- /**
- *ReadstheentirefileintoaListwitheachelementbeingaString[]of
- *tokens.
- *
- *@returnaListofString[],witheachString[]representingalineofthe
- *file.
- *
- *@throwsIOException
- *ifbadthingshappenduringtheread
- */
- publicListreadAll()throwsIOException{
- ListallElements=newArrayList();
- while(hasNext){
- String[]nextLineAsTokens=readNext();
- if(nextLineAsTokens!=null)
- allElements.add(nextLineAsTokens);
- }
- returnallElements;
- }
- /**
- *Readsthenextlinefromthebufferandconvertstoastringarray.
- *
- *@returnastringarraywitheachcomma-separatedelementasaseparate
- *entry.
- *
- *@throwsIOException
- *ifbadthingshappenduringtheread
- */
- publicString[]readNext()throwsIOException{
- StringnextLine=getNextLine();
- returnhasNext?parseLine(nextLine):null;
- }
- /**
- *Readsthenextlinefromthefile.
- *
- *@returnthenextlinefromthefilewithouttrailingnewline
- *@throwsIOException
- *ifbadthingshappenduringtheread
- */
- privateStringgetNextLine()throwsIOException{
- if(!this.linesSkiped){
- for(inti=0;i<skipLines;i++){
- br.readLine();
- }
- this.linesSkiped=true;
- }
- StringnextLine=br.readLine();
- if(nextLine==null){
- hasNext=false;
- }
- returnhasNext?nextLine:null;
- }
- /**
- *ParsesanincomingStringandreturnsanarrayofelements.
- *
- *@paramnextLine
- *thestringtoparse
- *@returnthecomma-tokenizedlistofelements,ornullifnextLineisnull
- *@throwsIOExceptionifbadthingshappenduringtheread
- */
- privateString[]parseLine(StringnextLine)throwsIOException{
- if(nextLine==null){
- returnnull;
- }
- ListtokensOnThisLine=newArrayList();
- StringBuffersb=newStringBuffer();
- booleaninQuotes=false;
- do{
- if(inQuotes){
- //continuingaquotedsection,reappendnewline
- sb.append("\n");
- nextLine=getNextLine();
- if(nextLine==null)
- break;
- }
- for(inti=0;i<nextLine.length();i++){
- charc=nextLine.charAt(i);
- if(c==quotechar){
- //thisgetscomplex...thequotemayendaquotedblock,orescapeanotherquote.
- //doa1-charlookahead:
- if(inQuotes//weareinquotes,thereforetherecanbeescapedquotesinhere.
- &&nextLine.length()>(i+1)//thereisindeedanothercharactertocheck.
- &&nextLine.charAt(i+1)==quotechar){//..andthatchar.isaquotealso.
- //wehavetwoquotecharsinarow==onequotechar,soconsumethembothand
- //putoneonthetoken.wedo*not*exitthequotedtext.
- sb.append(nextLine.charAt(i+1));
- i++;
- }else{
- inQuotes=!inQuotes;
- //thetrickycaseofanembeddedquoteinthemiddle:a,bc"d"ef,g
- if(i>2//notonthebeginingoftheline
- &&nextLine.charAt(i-1)!=this.separator//notatthebeginingofanescapesequence
- &&nextLine.length()>(i+1)&&
- nextLine.charAt(i+1)!=this.separator//notattheendofanescapesequence
- ){
- sb.append(c);
- }
- }
- }elseif(c==separator&&!inQuotes){
- tokensOnThisLine.add(sb.toString());
- sb=newStringBuffer();//startworkonnexttoken
- }else{
- sb.append(c);
- }
- }
- }while(inQuotes);
- tokensOnThisLine.add(sb.toString());
- return(String[])tokensOnThisLine.toArray(newString[0]);
- }
- /**
- *Closestheunderlyingreader.
- *
- *@throwsIOExceptioniftheclosefails
- */
- publicvoidclose()throwsIOException{
- br.close();
- }
- }
- packageau.com.bytecode.opencsv;
- /**
- Copyright2005BytecodePtyLtd.
- LicensedundertheApacheLicense,Version2.0(the"License");
- youmaynotusethisfileexceptincompliancewiththeLicense.
- YoumayobtainacopyoftheLicenseat
- http://www.apache.org/licenses/LICENSE-2.0
- Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- SeetheLicenseforthespecificlanguagegoverningpermissionsand
- limitationsundertheLicense.
- */
- importjava.io.IOException;
- importjava.io.PrintWriter;
- importjava.io.Reader;
- importjava.io.Writer;
- importjava.math.BigDecimal;
- importjava.sql.Clob;
- importjava.sql.ResultSet;
- importjava.sql.ResultSetMetaData;
- importjava.sql.SQLException;
- importjava.sql.Time;
- importjava.sql.Timestamp;
- importjava.sql.Types;
- importjava.text.SimpleDateFormat;
- importjava.util.Iterator;
- importjava.util.List;
- /**
- *AverysimpleCSVwriterreleasedunderacommercial-friendlylicense.
- *
- *@authorGlenSmith
- *
- */
- publicclassCSVWriter{
- privateWriterrawWriter;
- privatePrintWriterpw;
- privatecharseparator;
- privatecharquotechar;
- privatecharescapechar;
- privateStringlineEnd;
- /**Thecharacterusedforescapingquotes.*/
- publicstaticfinalcharDEFAULT_ESCAPE_CHARACTER='"';
- /**Thedefaultseparatortouseifnoneissuppliedtotheconstructor.*/
- publicstaticfinalcharDEFAULT_SEPARATOR=',';
- /**
- *Thedefaultquotecharactertouseifnoneissuppliedtothe
- *constructor.
- */
- publicstaticfinalcharDEFAULT_QUOTE_CHARACTER='"';
- /**Thequoteconstanttousewhenyouwishtosuppressallquoting.*/
- publicstaticfinalcharNO_QUOTE_CHARACTER='\u0000';
- /**Theescapeconstanttousewhenyouwishtosuppressallescaping.*/
- publicstaticfinalcharNO_ESCAPE_CHARACTER='\u0000';
- /**Defaultlineterminatorusesplatformencoding.*/
- publicstaticfinalStringDEFAULT_LINE_END="\n";
- privatestaticfinalSimpleDateFormat
- TIMESTAMP_FORMATTER=
- newSimpleDateFormat("dd-MMM-yyyyHH:mm:ss");
- privatestaticfinalSimpleDateFormat
- DATE_FORMATTER=
- newSimpleDateFormat("dd-MMM-yyyy");
- /**
- *ConstructsCSVWriterusingacommafortheseparator.
- *
- *@paramwriter
- *thewritertoanunderlyingCSVsource.
- */
- publicCSVWriter(Writerwriter){
- this(writer,DEFAULT_SEPARATOR);
- }
- /**
- *ConstructsCSVWriterwithsuppliedseparator.
- *
- *@paramwriter
- *thewritertoanunderlyingCSVsource.
- *@paramseparator
- *thedelimitertouseforseparatingentries.
- */
- publicCSVWriter(Writerwriter,charseparator){
- this(writer,separator,DEFAULT_QUOTE_CHARACTER);
- }
- /**
- *ConstructsCSVWriterwithsuppliedseparatorandquotechar.
- *
- *@paramwriter
- *thewritertoanunderlyingCSVsource.
- *@paramseparator
- *thedelimitertouseforseparatingentries
- *@paramquotechar
- *thecharactertouseforquotedelements
- */
- publicCSVWriter(Writerwriter,charseparator,charquotechar){
- this(writer,separator,quotechar,DEFAULT_ESCAPE_CHARACTER);
- }
- /**
- *ConstructsCSVWriterwithsuppliedseparatorandquotechar.
- *
- *@paramwriter
- *thewritertoanunderlyingCSVsource.
- *@paramseparator
- *thedelimitertouseforseparatingentries
- *@paramquotechar
- *thecharactertouseforquotedelements
- *@paramescapechar
- *thecharactertouseforescapingquotecharsorescapechars
- */
- publicCSVWriter(Writerwriter,charseparator,charquotechar,charescapechar){
- this(writer,separator,quotechar,escapechar,DEFAULT_LINE_END);
- }
- /**
- *ConstructsCSVWriterwithsuppliedseparatorandquotechar.
- *
- *@paramwriter
- *thewritertoanunderlyingCSVsource.
- *@paramseparator
- *thedelimitertouseforseparatingentries
- *@paramquotechar
- *thecharactertouseforquotedelements
- *@paramlineEnd
- *thelinefeedterminatortouse
- */
- publicCSVWriter(Writerwriter,charseparator,charquotechar,StringlineEnd){
- this(writer,separator,quotechar,DEFAULT_ESCAPE_CHARACTER,lineEnd);
- }
- /**
- *ConstructsCSVWriterwithsuppliedseparator,quotechar,escapecharandlineending.
- *
- *@paramwriter
- *thewritertoanunderlyingCSVsource.
- *@paramseparator
- *thedelimitertouseforseparatingentries
- *@paramquotechar
- *thecharactertouseforquotedelements
- *@paramescapechar
- *thecharactertouseforescapingquotecharsorescapechars
- *@paramlineEnd
- *thelinefeedterminatortouse
- */
- publicCSVWriter(Writerwriter,charseparator,charquotechar,charescapechar,StringlineEnd){
- this.rawWriter=writer;
- this.pw=newPrintWriter(writer);
- this.separator=separator;
- this.quotechar=quotechar;
- this.escapechar=escapechar;
- this.lineEnd=lineEnd;
- }
- /**
- *WritestheentirelisttoaCSVfile.Thelistisassumedtobea
- *String[]
- *
- *@paramallLines
- *aListofString[],witheachString[]representingalineof
- *thefile.
- */
- publicvoidwriteAll(ListallLines){
- for(Iteratoriter=allLines.iterator();iter.hasNext();){
- String[]nextLine=(String[])iter.next();
- writeNext(nextLine);
- }
- }
- protectedvoidwriteColumnNames(ResultSetMetaDatametadata)
- throwsSQLException{
- intcolumnCount=metadata.getColumnCount();
- String[]nextLine=newString[columnCount];
- for(inti=0;i<columnCount;i++){
- nextLine[i]=metadata.getColumnName(i+1);
- }
- writeNext(nextLine);
- }
- /**
- *WritestheentireResultSettoaCSVfile.
- *
- *ThecallerisresponsibleforclosingtheResultSet.
- *
- *@paramrstherecordsettowrite
- *@paramincludeColumnNamestrueifyouwantcolumnnamesintheoutput,falseotherwise
- *
- */
- publicvoidwriteAll(java.sql.ResultSetrs,booleanincludeColumnNames)throwsSQLException,IOException{
- ResultSetMetaDatametadata=rs.getMetaData();
- if(includeColumnNames){
- writeColumnNames(metadata);
- }
- intcolumnCount=metadata.getColumnCount();
- while(rs.next())
- {
- String[]nextLine=newString[columnCount];
- for(inti=0;i<columnCount;i++){
- nextLine[i]=getColumnValue(rs,metadata.getColumnType(i+1),i+1);
- }
- writeNext(nextLine);
- }
- }
- privatestaticStringgetColumnValue(ResultSetrs,intcolType,intcolIndex)
- throwsSQLException,IOException{
- Stringvalue="";
- switch(colType)
- {
- caseTypes.BIT:
- Objectbit=rs.getObject(colIndex);
- if(bit!=null){
- value=String.valueOf(bit);
- }
- break;
- caseTypes.BOOLEAN:
- booleanb=rs.getBoolean(colIndex);
- if(!rs.wasNull()){
- value=Boolean.valueOf(b).toString();
- }
- break;
- caseTypes.CLOB:
- Clobc=rs.getClob(colIndex);
- if(c!=null){
- value=read(c);
- }
- break;
- caseTypes.BIGINT:
- caseTypes.DECIMAL:
- caseTypes.DOUBLE:
- caseTypes.FLOAT:
- caseTypes.REAL:
- caseTypes.NUMERIC:
- BigDecimalbd=rs.getBigDecimal(colIndex);
- if(bd!=null){
- value=""+bd.doubleValue();
- }
- break;
- caseTypes.INTEGER:
- caseTypes.TINYINT:
- caseTypes.SMALLINT:
- intintValue=rs.getInt(colIndex);
- if(!rs.wasNull()){
- value=""+intValue;
- }
- break;
- caseTypes.JAVA_OBJECT:
- Objectobj=rs.getObject(colIndex);
- if(obj!=null){
- value=String.valueOf(obj);
- }
- break;
- caseTypes.DATE:
- java.sql.Datedate=rs.getDate(colIndex);
- if(date!=null){
- value=DATE_FORMATTER.format(date);;
- }
- break;
- caseTypes.TIME:
- Timet=rs.getTime(colIndex);
- if(t!=null){
- value=t.toString();
- }
- break;
- caseTypes.TIMESTAMP:
- Timestamptstamp=rs.getTimestamp(colIndex);
- if(tstamp!=null){
- value=TIMESTAMP_FORMATTER.format(tstamp);
- }
- break;
- caseTypes.LONGVARCHAR:
- caseTypes.VARCHAR:
- caseTypes.CHAR:
- value=rs.getString(colIndex);
- break;
- default:
- value="";
- }
- if(value==null)
- {
- value="";
- }
- returnvalue;
- }
- privatestaticStringread(Clobc)throwsSQLException,IOException
- {
- StringBuffersb=newStringBuffer((int)c.length());
- Readerr=c.getCharacterStream();
- char[]cbuf=newchar[2048];
- intn=0;
- while((n=r.read(cbuf,0,cbuf.length))!=-1){
- if(n>0){
- sb.append(cbuf,0,n);
- }
- }
- returnsb.toString();
- }
- /**
- *Writesthenextlinetothefile.
- *
- *@paramnextLine
- *astringarraywitheachcomma-separatedelementasaseparate
- *entry.
- */
- publicvoidwriteNext(String[]nextLine){
- if(nextLine==null)
- return;
- StringBuffersb=newStringBuffer();
- for(inti=0;i<nextLine.length;i++){
- if(i!=0){
- sb.append(separator);
- }
- StringnextElement=nextLine[i];
- if(nextElement==null)
- continue;
- if(quotechar!=NO_QUOTE_CHARACTER)
- sb.append(quotechar);
- for(intj=0;j<nextElement.length();j++){
- charnextChar=nextElement.charAt(j);
- if(escapechar!=NO_ESCAPE_CHARACTER&&nextChar==quotechar){
- sb.append(escapechar).append(nextChar);
- }elseif(escapechar!=NO_ESCAPE_CHARACTER&&nextChar==escapechar){
- sb.append(escapechar).append(nextChar);
- }else{
- sb.append(nextChar);
- }
- }
- if(quotechar!=NO_QUOTE_CHARACTER)
- sb.append(quotechar);
- }
- sb.append(lineEnd);
- pw.write(sb.toString());
- }
- /**
- *Flushunderlyingstreamtowriter.
- *
- *@throwsIOExceptionifbadthingshappen
- */
- publicvoidflush()throwsIOException{
- pw.flush();
- }
- /**
- *Closetheunderlyingstreamwriterflushinganybufferedcontent.
- *
- *@throwsIOExceptionifbadthingshappen
- *
- */
- publicvoidclose()throwsIOException{
- pw.flush();
- pw.close();
- rawWriter.close();
- }
- }
以下是达人对此API做的测试:
http://blog.csdn.net/lord_is_layuping/archive/2008/02/14/2095766.aspx
我也做了测试,实际上直接调用API中的方法即可,不过还是应该看懂源码,感觉写的不错,对提高水平有很大的帮助,以后在开源项目方面要多看看。。。
发表评论
-
JAVA短信发送及JAVA发送http请求与处理
2016-06-22 14:34 679JAVA发送HTTP请求与处理参考: http://ww ... -
Java Zip应用
2016-06-22 14:30 708应用系统中使用jdk原生 ... -
模拟tomcat进行http请求及响应处理:BufferedReader类的readLine在socket网络编程应用时发生阻塞
2016-05-11 15:04 1847最近写一个简单的程序模拟tomcat进行http请求及响应 ... -
Castor-xml映射出现节点重复问题解决
2015-08-13 16:24 1221最近在使用Castor-xml生成XML时发现生成的格式不 ... -
Add directory entries问题
2014-08-05 10:24 1948用spring注解的项目,eclipse可以运行,打成jar ... -
BeanUtils.copyProperties与PropertyUtils.copyProperties用法及区别
2013-01-25 16:21 896http://www.cnblogs.com/fayf/ar ... -
java.net.BindException: Cannot assign requested address
2012-06-13 14:10 916转:http://wgkgood.blog.51cto ... -
Duplicate name in Manifest: Depends-On
2012-06-13 13:13 1667解决方法:http://ww2.sjc.edu/faculty ... -
java tree
2011-11-16 02:01 1311import java.util.ArrayList; im ... -
jacob操作word和excel
2011-07-28 17:00 917http://danadler.com/jacob/ -
获得PrepareStatement 的最终执行语句
2011-07-04 10:07 1034方法一:http://www.blogjava.net/ ... -
Non-terminating decimal expansion; no exact representable decimal result
2011-06-24 16:03 2629由于需要处理精度比较高的浮点数,所以弃用double类型,改用 ... -
JXLS应用示例
2011-06-03 01:41 3528JXLS在循环的记录前加序号: <jx:f ... -
月份加减方法处理
2011-06-03 00:52 936private static String monthAdd ... -
JAVA 5.0 后 自带监控工具 jps、jinfo、jstat、jma
2011-05-12 16:25 1255最近有个客户要进行WebLogic性能调优,但因为他们没有性能 ... -
定时器的实现、java定时器介绍与Spring中定时器的配置
2011-04-28 15:05 25651定时器的作用 在实际的开发中,如果项目中需要定时执行或者需 ... -
ClientAbortException,Connection reset by peer: socket write error
2011-03-07 11:24 6127extremetable导出excel,弹出一个下载窗口,这 ... -
java 调ireport (javaBean数据源)保存服务器 生成word
2011-02-24 14:40 1585package com.ztesoft.bidding.con ... -
JAVA包生成EXE应用实例
2011-01-06 15:35 1052相关文章:http://blog.csdn.net/fresh ... -
RMI客户端调用远程服务器方法-远程方法调用
2010-12-27 16:45 2768RMI软件下载:http://www.genady.net/r ...
相关推荐
**super-csv库**是由James Bogle创建的,它提供了一套丰富的API,支持Java程序员方便地进行CSV文件的读取和写入操作。`super-csv`的主要特点包括: 1. **高性能**:`super-csv`使用高效的代码实现,对大量数据的...
总的来说,这篇博客和提供的测试文件"SuperCSVTest"是学习和理解如何在Java中使用SuperCSV库进行CSV操作的宝贵资源。通过深入阅读和实践,开发者能够熟练掌握CSV文件的读写技巧,提高数据处理效率,并确保数据的一致...
Apache Commons CSV是Apache软件基金会开发的一个开源项目,用于处理CSV(逗号分隔值)文件。这个"commons-csv-1.8-bin.zip"文件包含了Apache Commons CSV库的1.8版本,它是一个二进制分发包,适用于Java开发者在...
在Java编程环境中,将Excel文件(.xls或.xlsx格式)转换为CSV文件是一项常见的任务,特别是在数据处理和分析中。本文将深入探讨如何利用Java来完成这个过程,主要使用Apache POI库,这是一个广泛使用的开源库,专门...
`javacsv.jar`是开源项目,由Dave Newton创建,它提供了一组方便的类和方法,帮助开发者轻松地与CSV数据交互。这个库已经被广泛采用,特别是对于那些需要快速实现CSV功能的项目,但不想依赖大型框架如Apache Commons...
`javacsv`是一个开源项目,由David Beites创建,它提供了一组简单的Java类,使得开发者可以方便地读取和写入CSV文件。`javacsv`库主要包含两个核心类:`CSVReader`和`CSVWriter`,分别用于读取和写入CSV数据。 1. ...
本项目关注的是如何使用Java编程语言将数据库中的记录导出为CSV(Comma Separated Values)格式的文件。CSV因其通用性和易于处理的特性,被广泛应用于数据交换。 首先,让我们深入了解CSV文件格式。CSV是一种简单的...
对于CSV文件,Java标准库没有内置的支持,但我们可以使用开源库如OpenCSV或Apache Commons CSV。解析CSV的基本步骤如下: 1. 创建CSVReader,传入文件流或文件路径。 2. 使用`readNext()`方法逐行读取CSV数据。 3. ...
在实际应用中,使用"javacsv.jar"库时,你需要将其添加到项目的类路径中,然后就可以导入相关的类和方法来操作CSV文件。例如,以下是一个简单的示例,展示了如何使用`CSVReader`和`CSVWriter`: ```java import ...
**SuperCSV-1.52** 是一个专为Java开发者设计的开源库,用于处理CSV(Comma Separated Values)文件。CSV文件是一种常见的数据交换格式,尤其在数据分析、电子表格和数据库导入导出中广泛应用。SuperCSV提供了一个...
总的来说,“java-jacoco-单元测试覆盖-示例项目”是一个实用的实践案例,它演示了如何在Java项目中集成JaCoCo进行单元测试覆盖率的计算和分析,对于初学者和开发者来说都是一个很好的学习资源。通过深入理解和运用...
通过学习和实践这些Java LINQ示例,开发者可以提升他们在数据处理方面的技能,提高代码的可读性和效率。同时,由于这些示例是针对Android优化的,因此对于Android开发者来说,这是一个了解如何在移动平台上高效处理...
标题中的"topia-service-csv-3.0-alpha-11.zip"暗示这是一个名为"topia-service-csv"的开源项目,版本号为3.0的alpha版本,具体是第11个迭代。通常,这样的命名规则用于软件或库的发布,其中CSV可能代表“Comma-...
NetCDF to CSV 使用了一些开源项目才能正常工作: [UNIDATA] - NetCDF 文件读取 [joda-time] - 日期和时间操作 [登录] - 登录! 安装 您将需要安装 java & maven。 $ git clone [git-repo-url] NetCDF-to-CSV $ ...
本文将详细介绍一个基于Java的开源库——`cs源码java-janusgraph-csv-importer`,它专门用于将CSV文件便捷地导入到JanusGraph中。 首先,我们来理解一下`cs源码java-janusgraph-csv-importer`。这个项目是一个Java...
为了在Java环境中操作这些文件,我们可以利用开源库如`mpxj`。 `mpxj`是一个强大的Java库,专门用于读取和写入MPP文件。它支持多种版本的Microsoft Project文件,包括.MPP和.MPT格式。在描述中提到的是`mpxj`的3.1...
CSV for Java是一个专为Java设计的开源库,它提供了方便的API以及命令行工具,使得开发者在处理CSV文件时能更加高效和灵活。 该库的核心功能包括: 1. **读取CSV文件**:CSV for Java提供了一套完整的API,允许...
要深入理解这个实例,你需要打开文件查看具体的Java代码,学习如何在Servlet中生成和发送CSV内容。 总之,CSV文件操作是Java开发中的常见任务,掌握相关知识对于数据处理和Web服务开发至关重要。了解如何读取、写入...
Java中处理CSV文件,通常可以使用开源库,如Apache Commons CSV、OpenCSV或uniVocity的csv-parser。这些库提供API来轻松地读取、解析和操作CSV数据。以Apache Commons CSV为例,我们可以创建一个`CSVParser`实例,...
在"基于Java的实例源码-OrientDB(基于Java的实例源码-文档数据库) 社区版.zip"这个压缩包中,包含了OrientDB社区版的源代码,这对于学习和理解OrientDB的工作原理以及如何在Java项目中集成它是极其宝贵的资源。...