日期:2014-05-20  浏览次数:20878 次

将数据库内容写出到.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();
}
}
}
------解决方案--------------------
write后面加个flush试下
------解决方案--------------------
也没有抛异常么。。。
------解决方案--------------------
你用的是new BufferedOutputStream(out); 应该是在缓存里面没有flush
------解决方案--------------------
没有flush
------解决方案--------------------
楼主你在循环内部进行:
bos = new FileOutputStream(txtFile);
buff = Question.getBytes();
bos.write(buff);

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

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


有中文的话不能用字节流,换个字符流试下print流不错
------解决方案--------------------
引用:
引用:现在写进去了,但是从数据库中读取出来是中文,写到.txt文档里面就成乱码了……求解决

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


中文可以用字节流啊,不会出现乱码