java实现数据库的数据写入到txt的方法
程序员文章站
2024-02-12 09:43:52
本文讲解如何用java实现把数据库的数据写入到txt中 并实现类似下载软件的样子在网页中弹出下载.
package datatest;
import jav...
本文讲解如何用java实现把数据库的数据写入到txt中 并实现类似下载软件的样子在网页中弹出下载.
package datatest; import java.io.bufferedoutputstream; import java.io.ioexception; import java.io.unsupportedencodingexception; import java.net.urlencoder; import java.sql.resultset; import java.sql.sqlexception; import javax.servlet.servletexception; import javax.servlet.servletoutputstream; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import bean.conndb; public class export extends httpservlet { public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //设置编码 response.setcharacterencoding("utf-8"); //连接数据库 conndb conn = new conndb(); servletoutputstream outputstream = null; bufferedoutputstream buffoutputstream = null; string txt_name = "导出的txt文件名.txt";//导出的txt文件名 try { response.reset();// 清空输出流 response.setcontenttype("text/plain;charset=utf-8"); //设置txt文件名称编码,防止中文乱码 response.setheader("content-disposition", "attachment; filename="+urlencoder.encode(txt_name, "utf-8")); stringbuffer write = new stringbuffer(); outputstream=response.getoutputstream(); buffoutputstream = new bufferedoutputstream(outputstream); //根据id查询数据库 int id=integer.parseint(request.getparameter("id")); string sql = "select a.id,name,account,password "; sql+="from test_rank a "; sql+="left join test_join b on b.id=a.id where a.id="+id; resultset rs = conn.doquery(sql); string content=""; try { while(rs.next()) { //把数据库中读取的数据写入 content=rs.getstring("name")+"\r\n";//在txt中换行为\t\n write.append(content); content=rs.getstring("account")+"\r\n"; write.append(content); break; } } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } //write.append(content); //设置编码 防止中文乱码 string str = new string(write.tostring().getbytes(),"gbk"); buffoutputstream.write(str.tostring().getbytes("gbk")); buffoutputstream.flush(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } finally { if (outputstream != null) try { outputstream.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } if (buffoutputstream != null) try { buffoutputstream.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } } public void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { this.doget(request, response); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: JS数组中对象去重操作示例
下一篇: 婴儿感冒鼻塞怎么办,快速有效的办法!