一个简单的下载文件的例子。
这里会出现什么情况呢?

@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws Exception {
String resourcePath = "/java4ye.txt";
URL resource = DemoApplication.class.getResource(resourcePath);
String path = resource.getPath().replace("%20", " ");
try( ServletOutputStream outputStream = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(path)) {
byte[] bytes = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
while ((len = fileInputStream.read(bytes)) != -1) {
baos.write(bytes, 0, len);
}
&n

本文讲述了在使用 try-with-resources 时遇到的一个问题,即在异常情况下,前端无法接收到错误信息。问题源于 try-with-resources 在异常发生时会提前关闭流,导致前端接收的响应为空。通过对比 try-catch 与 try-with-resources 的编译后代码,揭示了 try-with-resources 的关闭逻辑,并分析了其对异常处理的影响。最后,建议在使用 try-with-resources 时要留意异常时流的关闭情况。
最低0.47元/天 解锁文章
791

被折叠的 条评论
为什么被折叠?



