1
我已经编写了通过套接字传输文件的代码, 文件传输正常,但即使在调用.close()
方法后仍然未关闭。java socket fileoutputstream无法关闭文件
但是,关闭“套接字”后文件关闭,但我想保持连接打开。
这里服务器将文件发送到客户端
服务器代码
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();
}
什么是错的代码?
你怎么知道该文件没有关闭?这些更改是否写入磁盘? – 2013-03-13 12:29:20
该文件不能删除,重命名等...但文件大小是好的。然而,在关闭连接或终止程序后,它可以正常工作。 ... – 2013-03-13 12:55:10
我怀疑你的read()会阻塞,等待更多的信息到达,因此它不会终止并且你的文件没有关闭。也许读取预设数量的字节而不是等待-1? – 2013-03-13 13:16:18