JAVA讀取指定路徑下文件,實現模擬瀏覽器下載文件,核心代碼如下:
/**
* 瀏覽器下載
*
* @param sourceFilePath 源文件路徑:"D:\\demo.txt"
* @param fileName 下載生成的文件名
* @param response 響應瀏覽器
*/
public void browserDownload(String sourceFilePath, String fileName, HttpServletResponse response) {
try (InputStream is = new FileInputStream(sourceFilePath);
OutputStream os = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(os)) {
response.setContentType("application/octet-stream");
response.setHeader("content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), StandardCharsets.ISO_8859_1));
int length = 0;
byte[] temp = new byte[1024 * 10];
while ((length = bis.read(temp)) != -1) {
bos.write(temp, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}