java之文件下载和 File.separator简介

HttpServletResponse response下载

public void downLoadFile(String path,HttpServletResponse response) throws IOException {
        //下载的文件名称,带后缀
        String fileName=path.substring(path.lastIndexOf(File.separatorChar) + 1);
        response.reset();
        response.setContentType("application/octet-stream");//以流形式下载
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));//设置文件名称
        OutputStream out = response.getOutputStream();
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(path)));
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

ResponseEntity下载

下载接口

传递参数为要下载的文件的名字,然后拼接文件存放服务器的地址,把地址和文件名传递给文件下载方法。

@GetMapping("/{param}/downloadFile")
	public ResponseEntity<Resource> downloadFile(@PathVariable String param) {
		String downloadURl = uploadUrl + "/dev" + File.separator + param;
		return beginDownFile(downloadURl, param);
	}

文件下载方法

import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
/**
	 * 执行文件下载
	 * 
	 * @param param
	 * @return
	 */
	public ResponseEntity<Resource> beginDownFile(String downloadUrl, String param) {
		File file = new File(downloadUrl);
		Path path = Paths.get(file.getAbsolutePath());
		ByteArrayResource resource = null;
		try {
			resource = new ByteArrayResource(Files.readAllBytes(path));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ResponseEntity.ok().header("Content-Disposition", "attachment;filename=" + param)
				.contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream"))
				.body(resource);
	}

File.separator

简介

File.separator 的作用相当于 ’ \ ’

在 windows 中 文件文件分隔符 用 ’ \ ’ 或者 ’ / ’ 都可以

但是在 Linux 中,是不识别 ’ \ ’ 的,而 File.separator 是系统默认的文件分隔符号,在 UNIX 系统上,此字段的值为 ’ / ’

在 Microsoft Windows 系统上,它为 ’ \ ’ 屏蔽了这些系统的区别。

所以用 File.separator 保证了在任何系统下不会出错。

拓展

File 类还有:

1、separatorChar
与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。此字符串只包含一个字符

2、pathSeparatorChar
与系统有关的路径分隔符,为了方便,它被表示为一个字符串

3、pathSeparator
此字符用于分隔以路径列表形式给定的文件序列中的文件名
在 UNIX 系统上此字段为 ’ : ’
在 Microsoft Windows 系统上,它为 ’ ;’

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值