Source Code Cross Referenced for CSVParser.java in  » Groupware » hipergate » com » knowgate » misc » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Groupware » hipergate » com.knowgate.misc 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:          Copyright (C) 2003  Know Gate S.L. All rights reserved.
003:                              C/Oña, 107 1º2 28050 Madrid (Spain)
004:
005:          Redistribution and use in source and binary forms, with or without
006:          modification, are permitted provided that the following conditions
007:          are met:
008:
009:          1. Redistributions of source code must retain the above copyright
010:             notice, this list of conditions and the following disclaimer.
011:
012:          2. The end-user documentation included with the redistribution,
013:             if any, must include the following acknowledgment:
014:             "This product includes software parts from hipergate
015:             (http://www.hipergate.org/)."
016:             Alternately, this acknowledgment may appear in the software itself,
017:             if and wherever such third-party acknowledgments normally appear.
018:
019:          3. The name hipergate must not be used to endorse or promote products
020:             derived from this software without prior written permission.
021:             Products derived from this software may not be called hipergate,
022:             nor may hipergate appear in their name, without prior written
023:             permission.
024:
025:          This library is distributed in the hope that it will be useful,
026:          but WITHOUT ANY WARRANTY; without even the implied warranty of
027:          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
028:
029:          You should have received a copy of hipergate License with this code;
030:          if not, visit http://www.hipergate.org or mail to info@hipergate.org
031:         */
032:
033:        package com.knowgate.misc;
034:
035:        import java.io.File;
036:        import java.io.FileReader;
037:        import java.io.FileNotFoundException;
038:        import java.io.IOException;
039:        import java.io.UnsupportedEncodingException;
040:        import java.io.OutputStream;
041:        import java.io.FileOutputStream;
042:        import java.io.BufferedOutputStream;
043:        import java.io.Reader;
044:        import java.io.InputStreamReader;
045:        import java.io.FileInputStream;
046:
047:        import java.sql.Connection;
048:        import java.sql.SQLException;
049:        import java.sql.Date;
050:        import java.sql.CallableStatement;
051:
052:        import com.knowgate.debug.DebugFile;
053:        import com.knowgate.jdc.JDCConnection;
054:        import com.knowgate.misc.Gadgets;
055:        import com.knowgate.dataobjs.DB;
056:        import com.knowgate.dataobjs.DBBind;
057:        import com.knowgate.dataobjs.DBPersist;
058:
059:        /**
060:         * <p>Delimited Text Parser</p>
061:         * <p>Parses a delimited text file into a memory array</p>
062:         * @author Sergio Montoro Ten
063:         * @version 3.0
064:         */
065:        public class CSVParser {
066:
067:            private char cBuffer[]; // Buffer interno que contiene los caracteres del fichero a parsear
068:            private int iBuffer; // Longuitud del buffer interno
069:            private String ColNames[]; // Nombres de columnas leidos del descriptor de fichero
070:            private int RowPointers[]; // Punteros al inicio de cada línea en el buffer interno
071:            private int ColPointers[][]; // Punteros al inicio de cada columna en el buffer interno
072:            private int iCols; // Número de columnas contadas en el descriptor
073:            private int iRows; // Número de columnas contadas en el descriptor
074:            private int iErrLine; // Línea del fichero donde se produjo el último error de parseo
075:            private char cDelimiter;
076:            private boolean bQuoted;
077:            private String sCharSet;
078:
079:            // ----------------------------------------------------------
080:
081:            public CSVParser() {
082:                iBuffer = 0;
083:                sCharSet = null;
084:            }
085:
086:            // ----------------------------------------------------------
087:
088:            /**
089:             * Create CSV Parser and set encoding to be used
090:             * @param sCharSetName Name of charset encoding
091:             */
092:            public CSVParser(String sCharSetName) {
093:                iBuffer = 0;
094:                sCharSet = sCharSetName;
095:            }
096:
097:            // ----------------------------------------------------------
098:
099:            public String charSet() {
100:                return sCharSet;
101:            }
102:
103:            // ----------------------------------------------------------
104:
105:            public void charSet(String sCharSetName) {
106:                sCharSet = sCharSetName;
107:            }
108:
109:            // ----------------------------------------------------------
110:
111:            /**
112:             * Get line count
113:             * @return int
114:             * @since 3.0
115:             */
116:            public int getLineCount() {
117:                return iRows;
118:            }
119:
120:            // ----------------------------------------------------------
121:
122:            /**
123:             * Get column count
124:             * @return int
125:             * @since 3.0
126:             */
127:            public int getColumnCount() {
128:                return iCols;
129:            }
130:
131:            // ----------------------------------------------------------
132:
133:            public int errorLine() {
134:                return iErrLine;
135:            }
136:
137:            // ----------------------------------------------------------
138:
139:            public char getDelimiter() {
140:                return cDelimiter;
141:            }
142:
143:            // ----------------------------------------------------------
144:
145:            /**
146:             * <p>Parse data from a character array</p>
147:             * Parsed values are stored at an internal array in this CSVParser.
148:             * @param sFileDescriptor A list of column names separated by ',' ';' '|' '`' or '\t'.
149:             * Column names may be quoted. Lines are delimiter by '\n' characters<br>
150:             * Example 1) tx_mail,tx_name,tx_surname<br>
151:             * Example 2) "tx_name","tx_surname","tx_salutation"<br>
152:             * @throws ArrayIndexOutOfBoundsException Delimited values for a file is greater
153:             * than columns specified at descriptor.
154:             * @throws RuntimeException If delimiter is not one of { ',' ';' '|' '`' or '\t' }
155:             * @throws NullPointerException if sFileDescriptor is <b>null</b>
156:             * @throws IllegalArgumentException if sFileDescriptor is ""
157:             */
158:
159:            public void parseData(char[] aCharData, String sFileDescriptor)
160:                    throws ArrayIndexOutOfBoundsException, RuntimeException,
161:                    NullPointerException, IllegalArgumentException {
162:
163:                boolean bIgnore;
164:                char cAt;
165:
166:                if (DebugFile.trace) {
167:                    DebugFile.writeln("Begin CSVParser.parseData(char["
168:                            + String.valueOf(aCharData.length) + "], \""
169:                            + sFileDescriptor + "\")");
170:                    DebugFile.incIdent();
171:                }
172:
173:                bQuoted = false;
174:                cDelimiter = (char) 0;
175:                bIgnore = false;
176:
177:                if (aCharData != cBuffer) {
178:                    iBuffer = aCharData.length;
179:                    cBuffer = new char[iBuffer];
180:                    System.arraycopy(aCharData, 0, cBuffer, 0, iBuffer);
181:                }
182:
183:                iErrLine = 0;
184:
185:                if (DebugFile.trace)
186:                    DebugFile.writeln("trimming leading whitespaces");
187:
188:                // Ignorar los espacios en blanco al final del fichero
189:                for (int p = iBuffer - 1; p >= 0; p--) {
190:                    cAt = cBuffer[p];
191:                    if (cAt == ' ' || cAt == '\n' || cAt == '\r' || cAt == '\t')
192:                        iBuffer--;
193:                    else
194:                        break;
195:                }
196:
197:                if (iBuffer == 0) {
198:                    iRows = 0;
199:                    if (DebugFile.trace) {
200:                        DebugFile.decIdent();
201:                        DebugFile
202:                                .writeln("End CSVParser.parseData() : zero length array");
203:                    }
204:                    return;
205:                }
206:
207:                // Si el primer caracter no en blanco es comillas,
208:                // entonces se entiende que los campos van entrecomillados
209:
210:                int iFileDescLen = sFileDescriptor.length();
211:
212:                for (int p = 0; p < iBuffer; p++) {
213:                    cAt = sFileDescriptor.charAt(p);
214:
215:                    if (cAt != ' ' && cAt != '\t' && cAt != '\n' && cAt != '\r') {
216:                        bQuoted = (cAt == '"');
217:                        break;
218:                    }
219:                } // next
220:
221:                if (DebugFile.trace) {
222:                    if (bQuoted)
223:                        DebugFile.writeln("asume quoted identifiers");
224:                }
225:
226:                // Inferir el delimitador
227:
228:                for (int p = 0; p < iFileDescLen && cDelimiter == (char) 0; p++) {
229:
230:                    cAt = sFileDescriptor.charAt(p);
231:
232:                    if (cAt == '"')
233:                        bIgnore = !bIgnore;
234:                    if (!bIgnore) {
235:                        switch (cAt) {
236:                        case ',':
237:                            cDelimiter = ',';
238:                            break;
239:                        case ';':
240:                            cDelimiter = ';';
241:                            break;
242:                        case '|':
243:                            cDelimiter = '|';
244:                            break;
245:                        case '`':
246:                            cDelimiter = '`';
247:                            break;
248:                        case '\t':
249:                            cDelimiter = '\t';
250:                            break;
251:                        } // end switch()
252:                    } // fi ()
253:                } // next
254:
255:                if (DebugFile.trace) {
256:                    if (cDelimiter == (char) 0)
257:                        DebugFile
258:                                .writeln("error: cannot assign a valid column delimiter");
259:                }
260:
261:                if (cDelimiter == (char) 0)
262:                    throw new RuntimeException(
263:                            "Cannot assign a valid column delimiter");
264:
265:                // Almacenar los nombres de campo y contar el número de columnas
266:                ColNames = Gadgets.split(sFileDescriptor, new String(
267:                        new char[] { cDelimiter }));
268:                iCols = ColNames.length;
269:
270:                if (DebugFile.trace)
271:                    DebugFile.writeln("descriptor has " + String.valueOf(iCols)
272:                            + " columns");
273:
274:                if (bQuoted)
275:                    for (int c = 0; c < iCols; c++)
276:                        ColNames[c] = (ColNames[c].replace('"', ' ')).trim();
277:
278:                // Contar el número de filas a partir de los saltos de línea
279:                iRows = 1;
280:                for (int p = 0; p < iBuffer; p++) {
281:                    if (cBuffer[p] == '\n')
282:                        iRows++;
283:                } // next
284:
285:                if (DebugFile.trace)
286:                    DebugFile.writeln("input data has " + String.valueOf(iRows)
287:                            + " lines");
288:
289:                RowPointers = new int[iRows];
290:                ColPointers = new int[iRows][iCols];
291:
292:                int iRow = 0, iCol = 0;
293:
294:                if (DebugFile.trace)
295:                    DebugFile.writeln("parsing line 0");
296:
297:                RowPointers[iRow] = 0;
298:                ColPointers[iRow][iCol] = 0;
299:
300:                bIgnore = false;
301:
302:                for (int p = 0; p < iBuffer; p++) {
303:
304:                    cAt = cBuffer[p];
305:
306:                    if (cAt == '"' && bQuoted)
307:                        bIgnore = !bIgnore;
308:
309:                    if (!bIgnore) {
310:                        if (cAt == cDelimiter) {
311:                            iCol++;
312:                            if (iCol >= iCols) {
313:                                iErrLine = iRow + 1;
314:                                throw new ArrayIndexOutOfBoundsException(
315:                                        "Columns count mismatch for line "
316:                                                + String.valueOf(iErrLine)
317:                                                + " expected "
318:                                                + String.valueOf(iCols)
319:                                                + " but found more.");
320:                            } else
321:                                ColPointers[iRow][iCol] = p + 1;
322:                        } else if (cAt == '\n') {
323:                            if (iCol != iCols - 1) {
324:                                iErrLine = iRow + 1;
325:                                throw new ArrayIndexOutOfBoundsException(
326:                                        "Columns count mismatch for line "
327:                                                + String.valueOf(iErrLine)
328:                                                + " expected "
329:                                                + String.valueOf(iCols)
330:                                                + " and found only "
331:                                                + String.valueOf(iCol + 1));
332:                            }
333:                            iRow++;
334:                            iCol = 0;
335:
336:                            if (DebugFile.trace)
337:                                DebugFile.writeln("parsing line "
338:                                        + String.valueOf(iRow));
339:
340:                            RowPointers[iRow] = p + 1;
341:                            ColPointers[iRow][iCol] = p + 1;
342:                        }
343:                    } // fi (bIgnore)
344:                } // next
345:
346:                iErrLine = 0;
347:
348:                if (DebugFile.trace) {
349:                    DebugFile.decIdent();
350:                    DebugFile.writeln("End CSVParser.parseData()");
351:                }
352:            } // parseData
353:
354:            // ----------------------------------------------------------
355:
356:            /**
357:             * <p>Parse a delimited text file</p>
358:             * Parsed values are stored at an internal array in this CSVParser.<br>
359:             * File is readed using the character set specifid at constructor
360:             * @param oFile CSV File
361:             * @param sFileDescriptor A list of column names separated by ',' ';' '|' '`' or '\t'.
362:             * Column names may be quoted. Lines are delimiter by '\n' characters<br>
363:             * Example 1) tx_mail,tx_name,tx_surname<br>
364:             * Example 2) "tx_name","tx_surname","tx_salutation"<br>
365:             * @throws IOException
366:             * @throws FileNotFoundException
367:             * @throws ArrayIndexOutOfBoundsException Delimited values for a file is greater
368:             * than columns specified at descriptor.
369:             * @throws RuntimeException If delimiter is not one of { ',' ';' '|' '`' or '\t' }
370:             * @throws NullPointerException if oFile or sFileDescriptor are <b>null</b>
371:             * @throws IllegalArgumentException if sFileDescriptor is ""
372:             * @throws UnsupportedEncodingException
373:             * @since 3.0
374:             */
375:            public void parseFile(File oFile, String sFileDescriptor)
376:                    throws ArrayIndexOutOfBoundsException, IOException,
377:                    FileNotFoundException, RuntimeException,
378:                    NullPointerException, IllegalArgumentException,
379:                    UnsupportedEncodingException {
380:
381:                Reader oReader;
382:
383:                if (oFile == null)
384:                    throw new NullPointerException(
385:                            "CSVParser.parseFile() File parameter may not be null");
386:
387:                if (DebugFile.trace) {
388:                    DebugFile.writeln("Begin CSVParser.parseFile(\""
389:                            + oFile.getAbsolutePath() + "\",\""
390:                            + sFileDescriptor + "\")");
391:                    DebugFile.incIdent();
392:                }
393:
394:                if (sFileDescriptor == null) {
395:                    if (DebugFile.trace)
396:                        DebugFile.decIdent();
397:                    throw new NullPointerException(
398:                            "CSVParser.parseFile() File Descriptor parameter may not be null");
399:                }
400:
401:                if (sFileDescriptor.trim().length() == 0) {
402:                    if (DebugFile.trace)
403:                        DebugFile.decIdent();
404:                    throw new IllegalArgumentException(
405:                            "File Descriptor parameter may not be an empty string");
406:                }
407:
408:                iErrLine = 0;
409:
410:                iBuffer = new Long(oFile.length()).intValue();
411:
412:                if (iBuffer == 0) {
413:                    iRows = 0;
414:                    if (DebugFile.trace) {
415:                        DebugFile.decIdent();
416:                        DebugFile
417:                                .writeln("End CSVParser.parseFile() : zero length file");
418:                    }
419:                    return;
420:                }
421:
422:                cBuffer = new char[iBuffer];
423:
424:                if (null == sCharSet) {
425:                    oReader = new FileReader(oFile);
426:                } else {
427:                    oReader = new InputStreamReader(new FileInputStream(oFile),
428:                            sCharSet);
429:                }
430:                oReader.read(cBuffer);
431:                oReader.close();
432:                oReader = null;
433:
434:                parseData(cBuffer, sFileDescriptor);
435:
436:                if (DebugFile.trace) {
437:                    DebugFile.decIdent();
438:                    DebugFile.writeln("End CSVParser.parseFile()");
439:                }
440:            } // parseFile
441:
442:            // ----------------------------------------------------------
443:
444:            /**
445:             * <p>Parse a delimited text file</p>
446:             * Parsed values are stored at an internal array in this CSVParser.
447:             * @param sFilePath File Path
448:             * @param sFileDescriptor A list of column names separated by ',' ';' '|' '`' or '\t'.
449:             * Column names may be quoted. Lines are delimiter by '\n' characters<br>
450:             * Example 1) tx_mail,tx_name,tx_surname<br>
451:             * Example 2) "tx_name","tx_surname","tx_salutation"<br>
452:             * @throws IOException
453:             * @throws FileNotFoundException
454:             * @throws ArrayIndexOutOfBoundsException Delimited values for a file is greater
455:             * than columns specified at descriptor.
456:             * @throws RuntimeException If delimiter is not one of { ',' ';' '|' '`' or '\t' }
457:             * @throws NullPointerException if oFile or sFileDescriptor are <b>null</b>
458:             * @throws IllegalArgumentException if sFileDescriptor is ""
459:             * @throws UnsupportedEncodingException
460:             */
461:            public void parseFile(String sFilePath, String sFileDescriptor)
462:                    throws ArrayIndexOutOfBoundsException, IOException,
463:                    FileNotFoundException, RuntimeException,
464:                    NullPointerException, IllegalArgumentException,
465:                    UnsupportedEncodingException {
466:                parseFile(new File(sFilePath), sFileDescriptor);
467:            }
468:
469:            // ----------------------------------------------------------
470:
471:            /**
472:             * @param sColumnName Column Name
473:             * @return Zero based index for column position or -1 if column was not found.
474:             */
475:            public int getColumnPosition(String sColumnName) {
476:
477:                if (DebugFile.trace) {
478:                    DebugFile.writeln("Begin CSVParser.getColumnPosition("
479:                            + sColumnName + ")");
480:                    DebugFile.incIdent();
481:                }
482:
483:                int iPos = -1;
484:
485:                for (int c = 0; c < iCols; c++) {
486:                    if (ColNames[c].equalsIgnoreCase(sColumnName)) {
487:                        iPos = c;
488:                        break;
489:                    }
490:                } // next
491:
492:                if (DebugFile.trace) {
493:                    DebugFile.decIdent();
494:                    DebugFile.writeln("End CSVParser.getColumnPosition() : "
495:                            + String.valueOf(iPos));
496:                }
497:
498:                return iPos;
499:            } // getColumnPosition
500:
501:            // ----------------------------------------------------------
502:
503:            /**
504:             * <p>Get line from a parsed file.</p>
505:             * Lines are delimited by the Line Feed (LF, CHAR(10), '\n') character
506:             * @param iLine Line Number [0..getLineCount()-1]
507:             * @return Full Text for Line. If iLine<0 or iLine>=getLineCount() then <b>null</b>
508:             * @throws IllegalStateException If parseFile() has not been called prior to getLine()
509:             * @throws UnsupportedEncodingException
510:             */
511:            public String getLine(int iLine) throws IllegalStateException,
512:                    UnsupportedEncodingException {
513:                String sRetVal;
514:                int iStart, iEnd;
515:
516:                if (DebugFile.trace) {
517:                    DebugFile.writeln("Begin CSVParser.getLine("
518:                            + String.valueOf(iLine) + ")");
519:                    DebugFile.incIdent();
520:                }
521:
522:                if (0 == iBuffer)
523:                    throw new IllegalStateException(
524:                            "Must call parseFile() on a valid non-empty delimited file before calling getField() method");
525:
526:                if (iLine < 0 || iLine > iRows - 1)
527:
528:                    sRetVal = null;
529:
530:                else {
531:
532:                    iStart = ColPointers[iLine][0];
533:                    iEnd = iBuffer;
534:
535:                    // Search for line feed
536:                    for (int p = iStart; p < iBuffer; p++)
537:                        if (cBuffer[p] == '\n') {
538:                            iEnd = p;
539:                            break;
540:                        } // fi ()
541:
542:                    if (iStart == iEnd)
543:                        sRetVal = "";
544:                    else {
545:                        // Remove last Carriage Return (CR, CHAR(13), '\r') character
546:                        if (iEnd - 1 > iStart) {
547:                            if (cBuffer[iEnd - 1] == '\r')
548:                                --iEnd;
549:                            if (iStart == iEnd)
550:                                sRetVal = "";
551:                            else
552:                                sRetVal = new String(cBuffer, iStart, iEnd
553:                                        - iStart);
554:                        } else {
555:                            if (cBuffer[iStart] == '\r')
556:                                sRetVal = "";
557:                            else
558:                                sRetVal = new String(cBuffer, iStart, iEnd
559:                                        - iStart);
560:                        }
561:                    }
562:
563:                } // fi (iRow<0 || iRow>iRows-1)
564:
565:                if (DebugFile.trace) {
566:                    DebugFile.decIdent();
567:                    DebugFile.writeln("End CSVParser.getLine() : " + sRetVal);
568:                }
569:
570:                return sRetVal;
571:            } // getLine
572:
573:            // ----------------------------------------------------------
574:
575:            /**
576:             * <p>Get value for a field at a given row and column.</p>
577:             * Column indexes are zero based.<br>
578:             * Row indexes range from 0 to getLineCount()-1.
579:             * @param iCol Column Index
580:             * @param iRow Row Index
581:             * @return Field Value
582:             * @throws IllegalStateException If parseFile() method was not called prior to
583:             * getField()
584:             * @throws ArrayIndexOutOfBoundsException If Column or Row Index is out of bounds.
585:             * @throws StringIndexOutOfBoundsException If Row is malformed.
586:             * @throws UnsupportedEncodingException If charset encoding name is not recognized.
587:             */
588:            public String getField(int iCol, int iRow)
589:                    throws IllegalStateException,
590:                    ArrayIndexOutOfBoundsException,
591:                    StringIndexOutOfBoundsException,
592:                    UnsupportedEncodingException {
593:                int iStart;
594:                int iEnd;
595:                String sRetVal;
596:
597:                if (DebugFile.trace) {
598:                    DebugFile.writeln("Begin CSVParser.getField("
599:                            + String.valueOf(iCol) + "," + String.valueOf(iRow)
600:                            + ")");
601:                    if (iBuffer > 0)
602:                        DebugFile.incIdent();
603:                }
604:
605:                iErrLine = 0;
606:
607:                if (0 == iBuffer)
608:                    throw new IllegalStateException(
609:                            "Must call parseFile() on a valid non-empty delimited file before calling getField() method");
610:
611:                if (-1 == iCol || -1 == iRow) {
612:                    if (DebugFile.trace) {
613:                        DebugFile.decIdent();
614:                        DebugFile.writeln("End CSVParser.getField() : null");
615:                    }
616:                    return null;
617:                }
618:
619:                iErrLine = iRow;
620:
621:                iStart = ColPointers[iRow][iCol];
622:
623:                if (DebugFile.trace)
624:                    DebugFile.writeln("iStart=" + String.valueOf(iStart));
625:
626:                if (iCol < iCols - 1)
627:                    iEnd = ColPointers[iRow][iCol + 1] - 1;
628:                else if (iRow < iRows - 1)
629:                    iEnd = ColPointers[iRow + 1][0] - 1;
630:                else
631:                    iEnd = iBuffer;
632:
633:                if (DebugFile.trace)
634:                    DebugFile.writeln("triming trailing spaces from "
635:                            + String.valueOf(iEnd));
636:
637:                if (iEnd > 0 && iEnd < iBuffer) {
638:                    if (bQuoted) {
639:                        while (cBuffer[iEnd - 1] == '\r'
640:                                || cBuffer[iEnd - 1] == ' '
641:                                || cBuffer[iEnd - 1] == '\t')
642:                            if (--iEnd == 0)
643:                                break;
644:                    } else {
645:                        if (cBuffer[iEnd - 1] == '\r')
646:                            iEnd--;
647:                    }
648:                } else if (iEnd < 0)
649:                    iEnd = 0;
650:
651:                if (DebugFile.trace)
652:                    DebugFile.writeln("iEnd=" + String.valueOf(iEnd));
653:
654:                if (iStart == iEnd)
655:                    sRetVal = "";
656:                else if (bQuoted)
657:                    sRetVal = new String(cBuffer, iStart + 1, iEnd - iStart - 2);
658:                else
659:                    sRetVal = new String(cBuffer, iStart, iEnd - iStart);
660:
661:                iErrLine = 0;
662:
663:                if (DebugFile.trace) {
664:                    DebugFile.decIdent();
665:                    DebugFile.writeln("End CSVParser.getField() : " + sRetVal);
666:                }
667:
668:                return sRetVal;
669:            } // getField
670:
671:            // ----------------------------------------------------------
672:
673:            /**
674:             * <p>Get value for a field at a given row and column.</p>
675:             * @param sCol Column name
676:             * @param iRow Row position [0..getLineCount()-1]
677:             * @throws IllegalStateException
678:             * @throws ArrayIndexOutOfBoundsException
679:             * @throws StringIndexOutOfBoundsException
680:             * @throws UnsupportedEncodingException
681:             * @return Field value
682:             */
683:            public String getField(String sCol, int iRow)
684:                    throws IllegalStateException,
685:                    ArrayIndexOutOfBoundsException,
686:                    StringIndexOutOfBoundsException,
687:                    UnsupportedEncodingException {
688:
689:                int iCol = getColumnPosition(sCol);
690:
691:                if (iCol == -1)
692:                    throw new ArrayIndexOutOfBoundsException("Column " + sCol
693:                            + " not found");
694:
695:                return getField(iCol, iRow);
696:            }
697:
698:            // ----------------------------------------------------------
699:
700:            /**
701:             * <p>Find first occurence of a value at a given column</p>
702:             * Search is case sensitive
703:             * @param iCol int Column index [0..getColumnCount()-1]
704:             * @param sVal String Value sought
705:             * @return int
706:             * @throws UnsupportedEncodingException
707:             * @since 3.0
708:             */
709:            public int find(int iCol, String sVal)
710:                    throws UnsupportedEncodingException {
711:                int iFound = -1;
712:                int r = 0;
713:                while (r < iRows) {
714:                    if (getField(iCol, r).equals(sVal)) {
715:                        iFound = r;
716:                        break;
717:                    }
718:                } // wend
719:                return iFound;
720:            } // find
721:
722:            // ----------------------------------------------------------
723:
724:            /**
725:             * <p>Find first occurence of a value at a given column</p>
726:             * Search is case insensitive
727:             * @param iCol int Column index [0..getColumnCount()-1]
728:             * @param sVal String Value sought
729:             * @return int
730:             * @throws UnsupportedEncodingException
731:             * @since 3.0
732:             */
733:            public int findi(int iCol, String sVal)
734:                    throws UnsupportedEncodingException {
735:                int iFound = -1;
736:                int r = 0;
737:                while (r < iRows) {
738:                    if (getField(iCol, r).equalsIgnoreCase(sVal)) {
739:                        iFound = r;
740:                        break;
741:                    }
742:                } // wend
743:                return iFound;
744:            } // findi
745:
746:            // ----------------------------------------------------------
747:
748:            /**
749:             * Write CSVParser matrix to an output stream
750:             * @param oStrm OutputStream
751:             * @throws IOException
752:             * @since 3.0
753:             */
754:            public void writeToStream(OutputStream oStrm) throws IOException {
755:                if (DebugFile.trace) {
756:                    DebugFile
757:                            .writeln("Begin CSVParser.writeToStream([OutputStream])");
758:                    DebugFile.incIdent();
759:                }
760:
761:                if (null != sCharSet)
762:                    oStrm.write(new String(cBuffer).getBytes(sCharSet));
763:                else
764:                    oStrm.write(new String(cBuffer).getBytes());
765:
766:                if (DebugFile.trace) {
767:                    DebugFile.decIdent();
768:                    DebugFile.writeln("End CSVParser.writeToStream()");
769:                }
770:            } // writeToStream
771:
772:            // ----------------------------------------------------------
773:
774:            /**
775:             * Write CSVParser matrix to delimited text file
776:             * @param oStrm OutputStream
777:             * @throws IOException
778:             * @throws SecurityException
779:             * @since 3.0
780:             */
781:            public void writeToFile(String sFilePath) throws IOException,
782:                    SecurityException {
783:                if (DebugFile.trace) {
784:                    DebugFile.writeln("Begin CSVParser.writeToFile("
785:                            + sFilePath + ")");
786:                    DebugFile.incIdent();
787:                }
788:                FileOutputStream oOutStrm = new FileOutputStream(sFilePath);
789:                BufferedOutputStream oOutBuff = new BufferedOutputStream(
790:                        oOutStrm);
791:
792:                writeToStream(oOutBuff);
793:
794:                oOutBuff.close();
795:                oOutStrm.close();
796:
797:                if (DebugFile.trace) {
798:                    DebugFile.decIdent();
799:                    DebugFile.writeln("End CSVParser.writeToFile()");
800:                }
801:            } // writeToFile
802:
803:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.