3

I understand the other Reader subclasses in java.io, but I can't think of a use case where I'd need a CharArrayReader or a StringReader when I already have data available as String or char[].

Is it because of compatibility? To "feed" a String or char[] into something that expects Reader as parameter?

ofalvai
  • 316
  • 6
  • 13

2 Answers2

3

I would not call it compatibility, it's flexibility.

You are right, some libraries that deal with character based data provide a method accepting a Reader. So the user of that library can choose any mechanism to feed that library.

If you have a file on the harddisk, use a FileReader. If you have an arbitrary InputStream, use an InputStreamReader (with an appropriate encoding). If you already have a simple String in your code, use a StringReader. And so on ...

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
1

In addition to what has been answered already, these classes are very handy when you write unit tests for a method that expects a reader.

Henry
  • 42,982
  • 7
  • 68
  • 84