在java中将Blob内容转换为CSV格式

时间:2018-01-05 08:02:28

标签: java arrays csv

我想在数据库中读取Blob内容存储库,并在java中以CSV格式将其写入HttpServletResponse。当我尝试将存储在Blob中的CSV内容的byte []写入响应时,CSV文件内容已损坏。

如果您有任何想法,请建议。

由于

2 个答案:

答案 0 :(得分:0)

以下是我的表现:

private static void sendResponse(Connection con, long id,
        HttpServletResponse resp, String filename) {
    try (PreparedStatement stmt = con.prepareStatement(
            "select CONTENT_TYPE,CONTENT "
                    + "from CONTENT_TABLE "
                    + "where ID=?")) {
        int ix = 0;
        stmt.setLong(++ix, id);
        try (ResultSet rs = stmt.executeQuery()) {
            if (rs.next()) {
                String type = rs.getString(1);
                Blob result = rs.getBlob(2);
                if (result != null) {
                    try (InputStream in = result.getBinaryStream()) {
                        resp.setContentType(type);
                        resp.setCharacterEncoding("ISO-8859-1");
                        resp.setHeader("Content-Disposition",
                                        "attachment;filename=" + filename);
                        resp.setHeader("Cache-Control", "public");
                        resp.setHeader("Pragma","");  
                        OutputStream out = resp.getOutputStream();
                        try {
                            byte buf[] = new byte[4096];
                            for (int n = in.read(buf); n > 0; n = in.read(buf)) {
                                out.write(buf, 0, n);
                            }
                        } finally {
                            out.close();
                        }
                    }
                }
            }
        }
    } catch (SQLException | IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

答案 1 :(得分:0)

我认为最简单的方法是将二进制数据转换为Base 64字符串表示。

Apache commons codec为您做到了这一点:

只需使用:

byte[] binaryData = someMethodToReadYourFileIntoBytes();
String encodedData = Base64.encodeBase64String(binaryData);`
//now just write that to your CSV output.

有关如何进行操作的更多信息和其他选项,请参阅javadoc

希望它有所帮助。

相关问题