gpt4 book ai didi

java - Android/Java - 如何检查 OutputStream 何时完成写入字节

转载 作者:行者123 更新时间:2023-12-01 08:10:45 27 4
gpt4 key购买 nike

我创建了一个服务器套接字,它接受来自客户端的连接,当建立连接时,使用写入字节的 OutputStream 将图像传输到它。我的问题是如何在关闭套接字连接之前检查 OutputStream 是否已完成写入字节,因为有时并非所有图像都正确传输。这是我正在使用的代码:

File photoFile = new File(getHeader); //getHeader is the file that i have to transfer
int size2 = (int) photoFile.length();
byte[] bytes2 = new byte[size2];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(photoFile));
buf.read(bytes2, 0, bytes2.length);
buf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
client.getOutputStream().write(bytes2, 0, size2); //client is the server socket

谢谢

最佳答案

My question is how can i check if the OutputStream has finished to write the bytes before close the socket connection, because sometimes not all the image is correctly transferred

不,你的问题是你假设 read()填充缓冲区。 OutputStream当写入返回时已完成写入。记住这一点:

while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}

这是Java中复制流的正确方法。你的不是。

您还假设文件大小适合 int,并且整个文件适合内存,并且在写入任何内容之前将整个文件(也许)读入内存会浪费时间和空间。上面的代码适用于 1 字节以上的任何大小的缓冲区。我通常使用8192字节。

关于java - Android/Java - 如何检查 OutputStream 何时完成写入字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17587996/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com