views:

155

answers:

3

Hello everyone!

Background story:

There are these Source and Result interfaces for XML. These are adapters between different XML technologies in Java. Instances of these classes represent DOM, SAX, JAXB, XML streams, XML events (and even more?).

The question:

So, is there something comparable for plain old strings? Some generalization between the following?

  • [Input|Output]Stream
  • Reader|Writer
  • StringBuffer
  • StringBuilder
  • CharBuffer (from NIO)
  • File (or Path for the JDK7-fans among us)
  • (and finally) CharSequence

Perhaps there is some common API (Apache commons something...?) which provides such functionality?

Clarifying example:

Usage with classic approach:

An interface needs to be able to read (write) characters from (to) all possible sources (results):

interface SomeInterface {
    readFrom(CharacterSequence source);
    readFrom(InputStream source);
    readFrom(Reader source);
    readFrom(File source);
    // ...
    writeTo(CharacterSequence result);
    writeTo(OutputStream result);
    writeTo(Writer result);
    writeTo(File result);
    // ...
}

Usage with intended approach:

With some imaginary CharacterSource and CharacterResult interfaces, read/write now possible with one method each:

interface SomeInterface {
    readFrom(CharacterSource source);
    writeTo(CharacterResult result);
}

Intended approach implementation, possible hierarchy:

interface CharacterSource
+ class CharBufferSource
+ class InputStreamSource
+ class ReaderSource
+ class FileSource
+ ...

interface CharacterResult
+ class CharBufferResult
+ class OutputStreamResult
+ class WriterResult
+ class FileResult
+ ...

If such functionality is not present, should I write an own mini-API? (for a larger API, I'm currently involved at)

What's about this?

+1  A: 

There's this (yep - Apache Commons).

JRL
Hm, utility classes, looks litte unhandy. But thanks anyway ;)
java.is.for.desktop
A: 

You can generalise your interface by using Reader and Writer. If you wish to read from / write to a File you can use FileReader / FileWriter. Likewise you can use other Reader / Writer implementations to read from / write to a String (i.e. CharSequence) or a stream.

Adamski
A: 

Aren't Google's common-io's InputSupplier and OutputSupplier similar things to my proposed interfaces? (A way to generalize all possible streams of input and output)

The strange thing is, the type parameter of Google's interfaces doesn't have any constraints (I was thinking of Closable or something).

java.is.for.desktop