Java Reference
In-Depth Information
/** The fields in the current String */
protected
protected
List
<
String
>
list
=
new
new
ArrayList
<>();
/** the separator char for this parser */
protected
protected
char
char
fieldSep
;
/** parse: break the input String into fields
* @return java.util.Iterator containing each field
* from the original as a String, in order.
*/
public
public
List
<
String
>
parse
(
String line
) {
StringBuffer sb
=
new
new
StringBuffer
();
list
.
clear
();
// recycle to initial state
int
int
i
=
0
;
iif
(
line
.
length
() ==
0
) {
list
.
add
(
line
);
return
return
list
;
}
ddo
{
sb
.
setLength
(
0
);
iif
(
i
<
line
.
length
() &&
line
.
charAt
(
i
) ==
'"'
)
i
=
advQuoted
(
line
,
sb
, ++
i
);
// skip quote
else
i
=
advPlain
(
line
,
sb
,
i
);
list
.
add
(
sb
.
toString
());
Debug
.
println
(
"csv"
,
sb
.
toString
());
i
++;
}
while
while
(
i
<
line
.
length
());
return
return
list
;
}
/** advQuoted: quoted field; return index of next separator */
protected
protected
int
int
advQuoted
(
String s
,
StringBuffer sb
,
int
int
i
)
{
int
int
j
;
int
int
len
=
s
.
length
();
for
for
(
j
=
i
;
j
<
len
;
j
++) {
iif
(
s
.
charAt
(
j
) ==
'"'
&&
j
+
1
<
len
) {
iif
(
s
.
charAt
(
j
+
1
) ==
'"'
) {
j
++;
// skip escape char
}
else
else iif
(
s
.
charAt
(
j
+
1
) ==
fieldSep
) {
//next delimeter
j
++;
// skip end quotes