代码之家  ›  专栏  ›  技术社区  ›  Karl Jamoralin

关闭流

  •  0
  • Karl Jamoralin  · 技术社区  · 14 年前

    请参见下面的代码:

    s = new Socket(nextHopIP, 3434);
    
                fileIn = new FileInputStream(fileName);
                fileOut = s.getOutputStream();
                buffer = new byte[bufferSize];
                pw = new PrintWriter(s.getOutputStream());
                br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    
                pw.println(fromIP);
                pw.println(toIP);
                pw.println(fileName.split("\\\\")[fileName.split("\\\\").length - 1]);
                pw.flush();
    
                //Send file
                fileTransferTime = System.currentTimeMillis();
                while((readFile = fileIn.read(buffer)) != -1) {
                    fileOut.write(buffer, 0, readFile);
                }
                pw.println("");
                pw.flush();
                fileIn.close();
                fileOut.close();
                br.readLine(); //error here
                fileTransferTime = System.currentTimeMillis() - fileTransferTime;
                System.out.println("File transfer time: " + fileTransferTime);
                pw.close();
                br.close();
                s.close();
    

    当它到达br.readline()时,将引发套接字关闭异常。到目前为止,我只关闭了输出流。在这种情况下,关闭输出流是否也会关闭输入流?

    谢谢!

    5 回复  |  直到 13 年前
        1
  •  2
  •   Daniel C. Sobral    13 年前

    来自API文档 java.net.Socket.getOutputStream

    Closing the returned OutputStream will close the associated socket.
    

    br 关闭,因为它修饰与套接字关联的输入流。奇怪,但真实。半闭合插座是可能的。

    还请注意,资源处理应按以下方式进行:

    Resource resource = acquire();
    try {
        Decorator decorated = decorate(resource);
        use(decorated);
        decorated.flush();
    } finally {
        resource.release();
    }
    

    (可能使用围绕习语执行。)

        2
  •  0
  •   David    14 年前

    当你关闭 FileInputStream 错误前两行,这也不能关闭 BufferedReader 既然它现在没有可供阅读的流?我在这里猜测,不是真正的Java家伙,但它是有意义的。

        3
  •  0
  •   Kru    14 年前

    据我所知,套接字应该处理其流的管理。因此,当关闭套接字时,它将关闭底层流。

    如果要关闭特定流,则应使用 shutdownInput() 而不是关闭输入套接字;同样的情况也存在于输出中。

        4
  •  0
  •   user85421    14 年前

    应该很容易测试(解决?)它,只需将输出流的关闭移动到末尾,在这里您将关闭套接字的输入流。

    或者只是检查Java文档 getOutputStream() :

    关闭返回的输出流将关闭关联的套接字。

    关闭套接字也将关闭输入流( close )

    关闭此套接字还将关闭套接字的inputstream和outputstream。

        5
  •  -2
  •   Community CDub    8 年前

    套接字的行为是高度依赖于平台的,因此您永远无法确保可用的文档或方法能够按预期工作。

    我认为关闭 OutputStream 导致基础套接字关闭。我有一个类似的问题,插座的行为不符合我之前问过的预期。

    This answer 指示关闭套接字的输出流确实会关闭基础套接字