gpt4 book ai didi

Java套接字文件发送

转载 作者:行者123 更新时间:2023-12-01 23:55:08 24 4
gpt4 key购买 nike

我正在使用 java 套接字编写客户端/服务器。这是我的代码:

服务器:

public void sendFile(File file) {
BufferedOutputStreambufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
int count;
FileInputStream in;
try {
in = new FileInputStream(file);
byte[] mybytearray = new byte[(int) file.length()];
while ((count = in.read(mybytearray)) > 0) {
bufferedOutputStream.write(mybytearray, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

客户:

public void downloadFile() {
BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
byte[] aByte = new byte[8192];
int count;
FileOutputStream in;
try {
in = new FileOutputStream("C://fis.txt");
while ((count = bufferedInputStream.read(aByte)) > 0) {
System.out.println(count); // <- nothing happens
in.write(aByte, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

为什么第二个函数中的 bufferedInputStream 为空?

最佳答案

BufferedOutputStream 在缓冲区已满之前不会写入数据。您需要刷新OutputStream:

bufferedOutputStream.flush();

关于Java套接字文件发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15745772/

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