看起來澤西不支持直接寫入OutputStream,但經過多次挖掘和合並後,我學到了一些不同的想法,我設法學到了這門課。
澤西支持通過一個InputStream插入WebResource柱方法,其讀取和寫入請求主體的內容。
我正在從ResultSet生成一個CSV文件,因此我編寫了一個擴展InputStream的類,並且在調用read()時,它從ResultSet獲取一條記錄並構建一行CSV文件,並返回一個來自線。每次調用read()時,都會返回下一個字符,直到整行返回,此時將從數據庫中讀取下一條記錄,並重復該過程,直到沒有記錄爲止。
我使用了一個名爲OpenCSV建庫中的CSV的文件行
public class ResultSetCsvInputStream extends InputStream {
private ResultSet rs;
private int columns;
private int ch;
private byte[] line;
/**
* Construct a new SchemaInputStream
* @param rs
* @throws SQLException
*/
public ResultSetCsvInputStream(ResultSet rs) throws SQLException {
this.rs = rs;
// write column names
ResultSetMetaData meta = rs.getMetaData();
columns = meta.getColumnCount();
String[] colNames = new String[columns];
for(int i = 0; i < colNames.length; i++) {
colNames[i] = meta.getColumnName(i+1);
}
writeLine(colNames);
}
private void writeLine(String[] ln) {
StringWriter strWriter = new StringWriter();
CSVWriter csv = new CSVWriter(strWriter);
csv.writeNext(ln);
line = strWriter.toString().getBytes(Charset.forName("UTF8"));
ch = 0;
}
@Override
public int read() throws IOException {
if(rs == null)
return -1;
// read the next line
if(line == null || ch >= line.length) {
// query next line
try {
if(rs.next()) {
String[] record = new String[columns];
for(int i = 0; i < record.length; i++) {
record[i] = rs.getString(i+1);
}
writeLine(record);
}
else {
rs = null;
return -1;
}
} catch (SQLException e) {
throw new IOException(e);
}
}
// read next character
return line[ch++] & 0xFF;
}
}