简体   繁体   中英

Java IO readers - how do they work?

I'm working on project where I need to read several files from the server. I was wondering if I can read the output and connect to somewhere else with the same instance. Apparently I can (see below).

Tried this pseudocode:

c.connect(google)
BufferedReader r1 = ... c.getInputStream();

c.connect(somewhereelse)
BufferedReader r2 = ... c.getInputStream();
print(r1)
print(r2)

And the output was correct.

I don't know how does IO streams works or what does this conn function returns (I'll check that during winter evenings :-))

Real question: Can I rely on the fact I'll always get correct data? ie Does buffered reader keep some reference to data object that is not anymore bound to connection itself?

No, I think you can't trust this code. InputStream needs a connection to fetch data. For example, if you open java.net.SocketInputStream (url connections use this stream) and see read method, you will see such code:

    // connection reset
    if (impl.isConnectionReset()) {
        throw new SocketException("Connection reset");
    }

a bit lower you can see, that stream tries to fetch buffered data if exists:

    /*
     * We receive a "connection reset" but there may be bytes still
     * buffered on the socket
     */
    if (gotReset) {...}

and lower is checking for a connections lost:

   /*
    * If we get here we are at EOF, the socket has been closed,
    * or the connection has been reset.
    */
    if (impl.isClosedOrPending()) {
        throw new SocketException("Socket closed");
    }

About your working implementation:

  • First guess is that you did not close your first connection. Linking c to another connection did not close previous one.
  • Second guess is that your data was buffered. By connection or by your buffer reader.

I could be wrong in my thoughts, but it seams to be true at first sight.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM