I am creating an abstract binding class for a Reader
and Writer
where the user doesn't have to reference each one individually.
Example: I have a FileStream
which inside of it houses both a FileReader
and FileWriter
.
The question I have refers to optimizing the class. I know I can't have two streams opened simultaneously due to concurrency, however I need to initialize them somewhere without having data leaks all over the place.
Are streams/readers/writers classified as being open, as soon as you initialize them, or are the 'pipes' only opened once the first read/write begins? I'm looking at the JavaDoc and don't see anything here about when the streams actually open up...
For those who do not understand what I am asking (ignoring try-catch blocks):
// does my reader become OPEN here?
BufferedReader br = new BufferedReader(new FileReader("foobar.txt"));
// or here, now that I have performed the first operation.
br.readLine();
They are open as soon as you construct them. There is no 'open' operation, so they are already open.
Discussion:
new FileInputStream(...)
and new FileOutputStream(...)
open the file, as they throw IOExceptions
about it. Practically every other input or output stream extends FilterInput/OutputStream,
with a FileInput/OutputStream
as its delegate (including socket input/output streams as a matter of fact). The FileInput/OutputStream
is created first in any such stack, ergo it is already open before the decorator streams, ergo they are already open too.
ByteArrayInput/OutputStreams
and StringReader/Writer
don't need opening at all.
Alternative solution: forget about re-inventing the wheel.
Java has a class that is specifically designed to allow for reading and writing to the same file: java.io.RandomAcessFile
So, if you have to wrap around... Use that class, instead of combining two other things that were never intended to be combined!
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.