gpt4 book ai didi

java套接字文件输出流无法关闭文件

转载 作者:行者123 更新时间:2023-12-01 04:48:46 25 4
gpt4 key购买 nike

我已经编写了通过套接字传输文件的代码,文件传输正确,但即使调用 .close() 方法后也没有关闭。

然而,关闭“套接字”后文件会关闭,但我想保持连接打开。

这里服务器将文件发送到客户端

服务器代码

public  void sendFile(String sfileName) throws IOException{
try{
in = new FileInputStream(sfileName);
out = socket.getOutputStream();
transferData(in,out);
}
finally {
in.close();
in = null;
System.gc();
}
}
private void transferData(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while(in.available()==0);
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.flush();
}

客户端代码:

public  void recieveFile(String rfileName) throws IOException{
try{
in = socket.getInputStream();
System.out.println("Reciever file : " + rfileName);
out = new FileOutputStream(rfileName);
transferData(in,out);
}
finally{
out.flush();
out.close();
out = null;
System.gc();
}
}
private void transferData(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while(in.available()==0);
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.flush();
}

代码有什么问题?

最佳答案

我认为你应该使用Socket.shutdownOutput()

关于java套接字文件输出流无法关闭文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15382191/

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