zoukankan      html  css  js  c++  java
  • 将字符串写入文本并下载该文本

    /**
      * 字节流,传入的字符串,输出文件;服务器不保存文件,不用指定文件路径
      *
      * @param response
      * @param count
      *            传入的字符串
      * @param fileName
      *            要保存的文件名
      * @return success or error
      * @throws Exception
      */
     public static String downStream(HttpServletResponse response, String count,
       String fileName) throws Exception {
      String msg = null;
      try {
       ServletOutputStream ou = response.getOutputStream();
       // 下载文件
       byte bb[] = count.getBytes();//获取内容的字节
       // ByteArrayInputStream把字节数组当作源的输入流
       ByteArrayInputStream fileInputStream = new ByteArrayInputStream(bb);

       response.setContentType("application/x-msdownload;charset=UTF-8");// 弹出下载的框
       int filelen = fileInputStream.available();
       response.setContentLength(filelen);// 下载统计文件大小的进度
       response.setHeader("Content-Disposition", "attachment; filename="
         + new String(fileName.getBytes(), "ISO-8859-1")); // 设置响应头和下载保存的文件名

       // response.setContentType("application/octet-stream;charset=UTF-8");
       // 下载框的信息
       if (fileInputStream != null) {
        // 文件太大时内存不能一次读出,要循环

        byte a[] = new byte[1024];
        int n = 0;
        while (n != -1) {
         n = fileInputStream.read(a);
         if (n > 0) {
          ou.write(a, 0, n);
         }
        }
       }

       fileInputStream.close();
       ou.close();

       msg = "success";
      } catch (Exception e) {
       e.printStackTrace();
       msg = "error";

      }
      return msg;
     }

    /**
      * 写入文本
      *
      * @param path
      *            如:d:/file/
      * @param content
      * @param fileName
      *            如:data.text
      * @return success or error
      */
     public static String writeFile(String path, String fileName, String content) {
      try {
       File pah = new File(path);
       File file = new File(path + "\" + fileName);
       if (!pah.exists()) {
        pah.mkdirs();
        file.createNewFile();
       }
       FileWriter write = new FileWriter(file);
       PrintWriter print = new PrintWriter(write);
       print.write(content);
       write.close();
       print.close();
       return "success";
      } catch (Exception e) {
       e.printStackTrace();
       return "error";
      }

     }

  • 相关阅读:
    IIS Post 大小超出允许的限制
    webpack从零开始第1课:安装webpack和webpack-dev-server
    React
    ubuntu 安装nodejs和git
    ubuntu 启用root用户方法
    ubuntu安装最新版node和npm
    MVC Dropdownlist数据绑定 默认值
    C#调用Excel VBA宏[转载]
    git download error processing
    mysqladmin 使用
  • 原文地址:https://www.cnblogs.com/qgc88/p/3481941.html
Copyright © 2011-2022 走看看