使用数据流进行文件下载

来源:互联网 发布:儿童编程课程 编辑:程序博客网 时间:2024/06/05 06:33

 

/**
  * 下载课程文件
  *
  * @param fileName
  * @return
  */
 public String download(String mLocalProductPath) {
  // String mFilePath="D://test.txt";
  PropertiesUtil mPropertiesUnit = new PropertiesUtil();
  Properties mProperties = mPropertiesUnit
    .getProperties("config.properties");
  String mProductRoot = mProperties.getProperty("productRoot");
  System.out.println(mProductRoot);

  String mFilePath = mProductRoot + mLocalProductPath;

  // 设置成以文件类型进行下载
  response.addHeader("Content-Disposition", "attachment; filename=/""
    + mFilePath + "/"");
  ServletOutputStream sos = null;
  FileInputStream fin = null;
  try {
   fin = new FileInputStream(mFilePath);
   int buf = 4096;
   byte buffer[] = new byte[buf];
   sos = response.getOutputStream();
   for (int size = 0; (size = fin.read(buffer)) != -1;) {
    sos.write(buffer, 0, size);
   }
   sos.flush();
  } catch (FileNotFoundException e) {
   System.out.println(e.getMessage());
  } catch (IOException e) {
   System.out.println(e.getMessage());
  } finally {
   if (fin != null) {
    try {
     fin.close();
    } catch (IOException e) {
     e.printStackTrace();
    }

   }
   if (sos != null) {
    try {
     sos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }

  return null;
 }