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

Java问题:文件传输完成后InputStream读取循环无法终止

问题描述

我在模拟文件上传/下载流程:从FileInputStream读取文件,通过OutputStream发送至中间服务器;中间服务器使用transferTo()将数据通过OutputStream发送至下载端的Socket;下载端从InputStream读取数据并通过FileOutputStream写入文件。文件传输可正常完成,但下载端的读取字节循环无法检测到流已结束。尝试过调用output.flush()和手动关闭输出流,问题仍未解决。

上传端代码

fis = new FileInputStream(transferFilePath);

byte[] dataBytes = new byte[1024];

int nread;
while ((nread = fis.read(dataBytes)) != -1) {
    output.write(dataBytes,0, nread);
    md.update(dataBytes, 0, nread);
}

output.flush();

中间服务器代码

OutputStream output;
InputStream input;
try {
    output = downloader.getOutputStream();
    input = sender.getInputStream();

    input.transferTo(output);

} catch (IOException e) {
    throw new RuntimeException(e);
}

下载端代码

InputStream inStream = transferSocket.getInputStream();
File targetFile = new File("targetFile");
OutputStream outStream = new FileOutputStream(targetFile);

byte[] dataBytes = new byte[1024];

int nread;
while ((nread = inStream.read(dataBytes)) != -1) {
    outStream.write(dataBytes,0, nread);
}

System.out.println("Should hit here but does not :(");
解决方案

关闭整个Socket连接而非仅关闭输入/输出流后,问题得到解决。原因在于Socket的输入流只有在连接被完全关闭时才会返回-1,仅关闭输出流或调用flush()无法触发流结束的信号,导致下载端的read()方法一直阻塞等待数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:25:22