简体   繁体   中英

java.io writers and readers - how do you know which should be used?

There are quite a few classes that extend java.io.Writer and java.io.Reader.

Are there circumstances where you should use one over another? What is the overall usefulness of each of them (why are there so many)?

Do they have difference "performance" attributes? They all just write/read from a stream - don't they?

Does anyone know of a write-up which will give me examples of where you would use one over another.

Same question applies to dealing with actual Files too. There seems to be more than one way to open a file stream to be read/written to.

Thanks.

The Name of the Reader says much about the use case.

FileReader / StringReader / CharArrayReader / InputStreamReader have different implementation to read from Files, Strings, CharArrays or InputStream. The usage depends on what your source is.

LineNumberReader / PushbackReader / BufferedReader don't work 'Standalone' you can combine them with another source-Reader. for example new BufferedReader( new FileReader(file) );

This Reader gives you methods for special cases you may want to do. BufferedReader to read line by line, or LineNumberReader to get the line number.

PipedReader are good to read data form on Part/Thread of your Program to another Part/Thread in combination with an PipedWriter . ...

... for special cases you can build Chains with Reader and Writer like the Decorator pattern.

That's a particular design pattern that they have chosen. Which class you need is based what on "what you need do". If you want to read from a file you then perhaps need a FileReader . With most of those classes you can wrap one into another to get the functionality you need.

Here's a nice question I've asked a while ago, about using right Writer class.

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