Вопрос

There are too many java.io classes, for some of them i really dont understand when we need them, for example:

ByteArrayInputStream, ByteArrayOutputStream

SequenceInputStream,

PushbackInputStream, PushbackReader

StringReader...

I mean some real-life usages

Can someone please explain...

Это было полезно?

Решение

I would say that your question is too wide.

However it is possible to give a very basic overview of java.io package. It contains interfaces and classes for data input and output operations, such as reading bytes from file. There are only few basic interfaces / classes:

  • DataInput / ObjectInput - readig Java primitives and objects
  • DataOutput / ObjectOutput - writing Java primitives and objects
  • InputStream - reading individual bytes
  • OutputStream - writing individial bytes
  • Reader - reading character data
  • Writer - writing character data

There are other useful interfaces (like Closeable), but these are less significant.


It is best if you read the JavaDoc of these classes. Some examples:

  1. It is pretty obvious that you would use FileOutputStream to write something into a file.
  2. Character data is represented by bytes (defined by character encoding), so you can wrap any output stream using OutputStreamWriter.
  3. You have byte[] and want to read from it just like from InputStream? Use ByteArrayInputStream.
  4. You want to be able to return read bytes back to the reader (usually only a single pass-through is supported)? Wrap your reader with PushbackReader.
  5. You have some String and want to read from it just like from Reader? Use StringReader.
  6. ...

So if you need some specific stream/reader/writer, check java.io package, search the internet and ask a question on SO if needed.


Of course then there is java.nio package, which you should know about. But that is for a different topic.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top