Write a JDBC ResultSet to a delimited text file

Write a JDBC ResultSet to delimited text file, using a specified delimiter.

Javadoc available at https://www.javatapas.com/docs/javatapas/sql/WriteResultSetToFile.html


public static void writeResultSetToFile(ResultSet rset, boolean includeFieldNames, String fileName, String delim) throws SQLException, IOException {

	ResultSetMetaData rsmd=rset.getMetaData();
	int colCount = rsmd.getColumnCount();

	PrintWriter writer = new PrintWriter(fileName);

	if (includeFieldNames){
		StringBuilder sb = new StringBuilder();
		for (int i = 1; i <= colCount; i++){
			sb.append(rsmd.getColumnName(i));
			if (i < colCount){sb.append(delim);}
		}
		writer.println(sb.toString());
	}

	while (rset.next()){

		StringBuilder sb2 = new StringBuilder();

		for (int i = 1; i <= colCount; i++){
			String value = rset.getString(i);
			if (value == null){value = "";}
			sb2.append(value);
			if (i < colCount){sb2.append(delim);}
		}

		writer.println(sb2.toString());

	}

	writer.flush();
	writer.close();

}