---
title: "获取webroot下的文件"
author: "erwin_king"
date: "2011-08-10T12:13:18Z"
tags: []
categories: ["编程语言"]
slug: "webroot"
draft: false
lastmod: "2011-08-10T12:13:18Z"
id: 1144496
url: "https://erwin-king.iteye.com/blog/1144496"
---

public static void downloadFile(String filePath, javax.servlet.http.HttpServletResponse response) {  
  String fileName = ""; //文件名，输出到用户的下载对话框  
  //从文件完整路径中提取文件名，并进行编码转换，防止不能正确显示中文名  
  try {  
   if (filePath.lastIndexOf("/") &gt; 0) {  
    fileName = new String(filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length()).getBytes(  
      "GB2312"), "ISO8859\_1");  
   } else if (filePath.lastIndexOf("\\\\") &gt; 0) {  
    fileName = new String(filePath.substring(filePath.lastIndexOf("\\\\") + 1, filePath.length()).getBytes(  
      "GB2312"), "ISO8859\_1");  
   }  
  } catch (Exception e) {  
  }  
  //打开指定文件的流信息  
  FileInputStream fs = null;  
  try {  
   fs = new FileInputStream(new File(filePath));  
  } catch (FileNotFoundException e) {  
   e.printStackTrace();  
   return;  
  }  
  //设置响应头和保存文件名  
  response.setContentType("APPLICATION/OCTET-STREAM");  
  response.setHeader("Content-Disposition", "attachment; filename=\\"" + fileName + "\\"");  
  //写出流信息  
  int b = 0;  
  try {  
   PrintWriter out = response.getWriter();  
   while ((b = fs.read()) != -1) {  
    out.write(b);  
   }  
   fs.close();  
   out.close();  
   System.out.println("文件下载完毕.");  
  } catch (Exception e) {  
   e.printStackTrace();  
   System.out.println("下载文件失败!");  
  }  
 }