Hie*_*ker 1 java android outputstream serversocket
我创建了一个服务器套接字,它接受来自客户端的连接,当建立连接时,使用写入字节的 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
Run Code Online (Sandbox Code Playgroud)
谢谢
我的问题是如何在关闭套接字连接之前检查 OutputStream 是否已完成写入字节,因为有时并非所有图像都正确传输
不,您的问题是您假设read()填充缓冲区。该OutputStream有当写完写的回报。记住这个:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Run Code Online (Sandbox Code Playgroud)
这是在 Java 中复制流的正确方法。你的不是。
您还假设文件大小适合int,并且整个文件适合内存,并且在写入任何内容之前将整个文件(可能)读入内存是浪费时间和空间。上面的代码适用于 1 个字节以上的任何大小的缓冲区。我通常使用 8192 字节。