java socket fileoutputstream无法关闭文件

时间:2013-03-13 10:06:54

标签: java sockets netbeans fileoutputstream

我写了一个用于通过套接字传输文件的代码, 文件正确传输但即使在调用.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();
}

代码有什么问题?

1 个答案:

答案 0 :(得分:0)

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