当前位置: 代码迷 >> J2SE >> 将数据库内容写出到.txt文件中,为什么小弟我这样写不进去呢,文件总是空?
  详细解决方案

将数据库内容写出到.txt文件中,为什么小弟我这样写不进去呢,文件总是空?

热度:6628   发布时间:2013-02-25 21:55:06.0
将数据库内容写出到.txt文件中,为什么我这样写不进去呢,文件总是空??
public void guideFile(HttpServletRequest request,HttpServletResponse response,CLS_VO_NoteQuestionTemplate_Query_I voTemplateId) throws IOException, FileUploadException{
String fileName = voTemplateId.getId() + ".txt" ;
File txtFile = new File(fileName);//配置路径

//写流文件到前端浏览器
ServletOutputStream out = response.getOutputStream();
//设置一个报头,用于提供一个推荐的文件名,并强制浏览器显示保存对话框
response.setHeader("Content-disposition", "attachment;filename=" + fileName);//file
// BufferedInputStream  bis = null;
OutputStream  bos = null ;
byte[] buff = new byte[2048];
try {
bos = new BufferedOutputStream(out);
CLS_VO_Result Result = boQuestionTemplate.query(voTemplateId);
Collection<CLS_VO_NoteQuestionTemplate> collection = (Collection<CLS_VO_NoteQuestionTemplate>) Result.getContent();
for (CLS_VO_NoteQuestionTemplate clsVONoteQuestionTemplate : collection) {
List<CLS_VO_NoteQuestionTemplate_Question> questionList = clsVONoteQuestionTemplate.getQaList();
for (CLS_VO_NoteQuestionTemplate_Question voQuestionTemplateQuestion : questionList) {
String Question = voQuestionTemplateQuestion.getQuestion();
bos = new FileOutputStream(txtFile);
buff = Question.getBytes();
bos.write(buff);
}
}

} catch (Exception e) {
e.printStackTrace();
}finally{
if(bos != null){
bos.close();
}
}
}楼主你在循环内部进行:
bos = new FileOutputStream(txtFile);
buff = Question.getBytes();
bos.write(buff);

这个不太妥当,意味着后面的会不断覆盖掉前面的,所以建议在最前面就把 FileOutputStream 准备好。

至于flush(),因为你finally中有使用 close(),应该不是问题。
引用:
现在写进去了,但是从数据库中读取出来是中文,写到.txt文档里面就成乱码了……求解决


有中文的话不能用字节流,换个字符流试下print流不错你用的是new BufferedOutputStream(out); 应该是在缓存里面没有flushwrite后面加个flush试下没有flush也没有抛异常么。。。
引用:
引用:现在写进去了,但是从数据库中读取出来是中文,写到.txt文档里面就成乱码了……求解决

有中文的话不能用字节流,换个字符流试下print流不错


中文可以用字节流啊,不会出现乱码
  相关解决方案