Java Reference
In-Depth Information
private
private final
final static
static
Pattern csvRE
=
Pattern
.
compile
(
CSV_PATTERN
);
public
public static
static
void
void
main
(
final
final
String
[]
argv
)
throws
throws
IOException
{
System
.
out
.
println
(
CSV_PATTERN
);
new
new
CSVRE
().
process
(
new
new
BufferedReader
(
new
new
InputStreamReader
(
System
.
in
)));
}
/** Process one file. Delegates to parse() a line at a time */
public
public
void
void
process
(
final
final
BufferedReader input
)
throws
throws
IOException
{
String line
;
// For each line...
while
while
((
line
=
input
.
readLine
()) !=
null
null
) {
System
.
out
.
println
(
"line = `"
+
line
+
"'"
);
final
final
List
<
String
>
list
=
parse
(
line
);
System
.
out
.
println
(
"Found "
+
list
.
size
() +
" items."
);
for
for
(
String str
:
list
) {
System
.
out
.
print
(
str
+
","
);
}
System
.
out
.
println
();
}
}
/** Parse one line.
* @return List of Strings, minus their double quotes
*/
public
public
List
<
String
>
parse
(
final
final
String line
) {
final
final
List
<
String
>
list
=
new
new
ArrayList
<>();
final
final
Matcher m
=
csvRE
.
matcher
(
line
);
// For each field
while
while
(
m
.
find
()) {
String match
=
m
.
group
();
iif
(
match
==
null
null
) {
break
break
;
}
iif
(
match
.
endsWith
(
","
)) {
// trim trailing ,
match
=
match
.
substring
(
0
,
match
.
length
() -
1
);
}
iif
(
match
.
startsWith
(
"\""
)) {
// must also end with \"
iif
(!
match
.
endsWith
(
"\""
)) {
throw
throw new
new
IllegalArgumentException
(
"Quoted column missing end quote: "
+
line
);
}
match
=
match
.
substring
(
1
,
match
.
length
() -
1
);