Hi I am trying to convert oracle jdbc resultset to csv file. Below is the code used. Issue occures when there is value like below in the field. It deforms the output csv and all this come in separate line rather than in one field.
Value in Field comes in csv as
[<333message:Runtime error in script' ProcessItem: ' Type: 'ITEM'" 1:0).Internal Script error: java.lang.NullPointerException
Script (line 1):
setHours = 0 ;
if(ts.instanceId == null)
" 3 : ts.instanceId = 0 ;"
Step >]
int ncols = result.getMetaData().getColumnCount();
System.out.println("ColumnCout"+ncols);
FileOutputStream fos=new FileOutputStream(new File("C:\\test.csv"),false);
Writer out = new OutputStreamWriter(new BufferedOutputStream(fos),"UTF_8");
for (int j=1; j<(ncols+1); j++) {
out.append(result.getMetaData().getColumnName (j));
if (j<ncols) out.append(","); else out.append("\r\n");
}
int m =1;
while (result.next()) {
for (int k=1; k<(ncols+1); k++) {
out.append(result.getString(k));
if (k<ncols) out.append(","); else out.append("\r\n");
}
//System.out.println("No of rows"+m);
m++;
}
Writing a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java.
Are you using "java.sql.ResultSet" class? If yes, see the library in this link http://opencsv.sourceforge.net/
See an example:
CSVWriter csvWriter = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
java.sql.ResultSet myResultSet = .... ;
csvWriter.writeAll(myResultSet, includeHeaders);
Get the value for the column that could have new lines as
String multiLine = null;
if (k == <col_index> && (mutiLine = rs.getString(k)) != null)
out.append(multiLine.replaceAll("\\n", ""));
else
out.append(result.getString(k));
You could filter all the columns as well but then would incur some performance hit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With