You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Socket文件传输中FileOutputStream无法正常关闭问题排查

问题描述

开发了一款支持文件与类对象共享的Socket程序,服务器端发送文件无报错,客户端能正确接收并存储大小小于21MB的PDF文件,且文件可正常打开,但接收完成后FileOutputStream无法正常关闭。已通过打印语句验证该问题,尝试过Lombok的@Cleanup注解以及try-with-resources方式,均未解决问题。

相关代码

Java客户端接收代码

Path dir = Paths.get("Temp");
if (Files.notExists(dir)) {
   Files.createDirectory(dir);
}
Path file = Files.createTempFile(dir, null, ".pdf");

InputStream inputStream = socket.getInputStream();

@Cleanup
FileOutputStream fileOutputStream = new FileOutputStream(file.toFile());

byte[] buffer = new byte[1024];
int bytesRead;

while ((bytesRead = inputStream.read(buffer)) > 0) {
   fileOutputStream.write(buffer, 0, bytesRead);
}

System.out.println("ok2");

Maven依赖配置

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
    <scope>provided</scope>
</dependency>

内容的提问来源于stack exchange,提问作者NaveenB2004

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 09:02:05