2

我有一个有一些值的结果集,我想将结果集中的数据导出为带有保存对话框的文本文件。

如何在 Java 中做到这一点?

我已经完成了对 excel 和 java 的上述要求,如下所示。

response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".xls\"");

response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\""); response.setContentType("application/pdf");

更新 :

if(exportTo.equals("text")){
            response.setContentType("text/plain");
            response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".txt\"");
            try {

            } catch (Exception e) {
                // TODO: handle exception
            }

        }

在这

在尝试块中,如何将结果集中可用的内容设置为输出流并使其可用。

4

1 回答 1

3

唯一的区别是:

response.setContentType("text/plain");

你可以在这里看到一个完整的例子(http://www.mkyong.com/servlet/servlet-code-to-download-text-file-from-website-java/

更新

这是我开发和测试过的演示,并且运行良好:

public class ServletDownloadDemo extends HttpServlet {
    private static final int BYTES_DOWNLOAD = 1024;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                                                                                       IOException {
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");

        String s = "Test\n\nText file contects!!";
        InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));

        int read = 0;
        byte[] bytes = new byte[BYTES_DOWNLOAD];
        OutputStream os = response.getOutputStream();

        while ((read = input.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        os.flush();
        os.close();
    }
}

它下载一个downloadname.txtString s.

更新 2

    String s = "";
    while (rs.next()) {
        s += rs.getString("column_name");
    }

    if (exportTo.equals("text")) {
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");

        try {
            InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));

            int read = 0;
            byte[] bytes = new byte[BYTES_DOWNLOAD];
            OutputStream os = response.getOutputStream();

            //data form resultset

            while ((read = input.read(bytes)) != -1) {
                os.write(bytes, 0, read);
            }
            os.flush();
            os.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

你必须填充你的ResultSet并放置你需要的东西String s就这样。

于 2012-09-26T11:45:00.727 回答