How to capture the field values in the csv file using bufferedreader
问题
The csv file looks like this
\$\$NAME$$ JOHN
\$\$STATE$$ CA
\$\$CITY$$ SF
\$\$REGION$$ XYZ
\$\$WEATHER$$
\$\$AGE$$ 25
\$\$GROUP$$ CATEGORY
\$\$TIME$$
5
5
5
I'm trying to get the field values like name, it is the value after \$\$NAME$$ (there is a space after the identifier). How do I store the value for each field by using BufferedReader in Java? The fields could be in any line number and not in a fixed place or format, and also throw out an error if there is any special characters or null value is encountered.
int n = 100; // Max lines
String line;
try (BufferedReader br = new BufferedReader(new FileReader(str)))
{
while ((line = br.readLine()) != null && i++ < n)
{
br.readLine();
line = br.readLine();
System.out.println(line);
}
}
Once the values are extracted from the CSV file, I need to store them in a string variable and use it later to insert into the database for each column values
Case 2:And also for the last field \$\$GROUP$$ CATEGORY the value is "5" in cell 9 to 11 and i need to match that the column CATEGORY in the database has to be 5 stored in a string to be inserted into the database column of the same name. The regex wont find the exact match when i used line.matches condition
解答
从csv 中,按“$$字段名$$ 字段值”格式,提取数据。用Java 实现则代码较长。
用Java 下的开源包 SPL 很容易写,只要 2 句:
A |
|
1 |
=file("data.csv").read@n().select(left(~,2)=="\$\$").(right(~,-2).split("$$")) |
2 |
=create(${A1.(~(1)).concat@c()}).record(A1.(~(2))) |
SPL 提供了 JDBC 供 Java 调用,把上面的脚本存为 csv2tbl.splx,在 Java 中以存储过程的方式调用脚本文件:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call csv2tbl()");
st.execute();
…
English version