【发布时间】:2013-03-01 04:53:02
【问题描述】:
我已经编写了一个通过套接字传输文件的代码,
文件传输正常,但调用.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();
}
代码有什么问题?
【问题讨论】:
-
怎么知道文件没有关闭?更改不会写入磁盘吗?
-
文件无法删除、重命名等...但文件大小还可以。但是在关闭连接或终止程序后,它可以工作。 ....
-
我怀疑您的 read() 将阻塞,等待更多信息到达,因此它没有终止并且您的文件没有关闭。也许读取预设数量的字节而不是等待-1?
-
但即使是文件也应该关闭,因为我已经将 close() 方法放在 finally 块中...]
-
available() 为零时旋转的循环实际上是在浪费时间。去掉它。以下读取将阻塞,而不是占用 CPU。
标签: java sockets netbeans fileoutputstream