JAVA下载TXT文件到本地,这一个方法完全能够解决

 public String selectBmb() throws Exception {
  String src = SystemConfig.getUploadPath() + "text.txt";
  String xsxm = this.formBean.getString("PHONE");
  String cxmm = this.formBean.getString("cxmm");
  java.io.File f = new java.io.File(src);
  BufferedWriter bw = null;
  bw = new BufferedWriter(new FileWriter(f));

  // 写入文件
  bw.write(xsxm + "\r\n" + cxmm);

  bw.flush();
  bw.close();

  // 下载打开文件

  String filePath = src;
  String fileName = "保存密码";

  //boolean isInline = false;
  out.clear();
  this.pageWrapper.response.reset();

  fileName = "保存密码" + ".txt";
  java.io.File f1 = new java.io.File(filePath);
  this.pageWrapper.response.setContentType("application/x-download");
  this.pageWrapper.response.setHeader(
    "Content-Disposition",
    "attachment;filename="
      + java.net.URLEncoder.encode(fileName, "UTF8"));
  this.pageWrapper.response.setContentLength((int) f1.length()); // ?
                  // 设置下载内容大小?
  if (fileName != null && filePath != null) {
   try {
    if (f.exists() && f.canRead()) {
     //String mimetype = null;
     byte[] buffer = new byte[4096]; // ? 缓冲区
     BufferedOutputStream output = null;
     BufferedInputStream input = null;
     try {
      output = new BufferedOutputStream(
        this.pageWrapper.response.getOutputStream());
      input = new BufferedInputStream(new FileInputStream(f));

      int n = (-1);
      while ((n = input.read(buffer, 0, 4096)) > -1) {
       output.write(buffer, 0, n);
      }
      this.pageWrapper.response.flushBuffer();
     } catch (Exception e) {
     } // ? 用户可能取消了下载
     finally {
      if (input != null)
       input.close();
      if (output != null)
       output.close();
     }
    }
    
   } catch (Exception ex) {
    ex.printStackTrace();
   }

  }
  return null;

 }

你可能感兴趣的:(Web前端)