将字符串写出文件,然后根据路径查找下载文件

        String time = QDateTime.dateToString(new Date(), "yyyy-MM-dd HH:mi:ss");
        time = time.replaceAll("-", "");
        time =time.replace(":", "");
        time =time.replace(" ", "");
        time = time.substring(2);
        String file_name = time + ".txt";
        String uploadDir = request.getRealPath("/resources") + "\\printTicket\\";
        File dirPath = new File(uploadDir);
        OutputStream fos =null;
        try {            
              if (!dirPath.exists()){
                  dirPath.mkdirs();
              }
            
              fos = new FileOutputStream(uploadDir+file_name);            
            fos.write(logTxt.getBytes());
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally{
            if(fos != null){
                fos.close();
            }
        }
        
//下载
        InputStream inStream = null;
        OutputStream out = null;
        try{        
//            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment; filename="+ file_name + "");    
            inStream = new FileInputStream(uploadDir+file_name);
            out = response.getOutputStream();
            byte[] buf = new byte[4096];
            int readLength;
            while (((readLength = inStream.read(buf)) != -1)){
                out.write(buf, 0, readLength);
            }

         }catch (Exception e) {
             log.error("读取文件内容出错");    
         }finally{
             if(out != null){
                 out.close();
             }
             if(inStream!=null){
                 inStream.close();
             }
         }

 

posted @ 2015-10-30 14:40  新手娃娃菜  阅读(193)  评论(0编辑  收藏  举报