Re: How to extend FilterInputStream to convert tabs to spaces?
On 3/8/2015 9:47 AM, fangyuncn@gmail.com wrote:
Hi, I need to write a class Tabs2SpaceInputStream, it extends java.io.FilterInputStream. the code snippet like this:
public class Tabs2SpaceInputStream extends FilterInputStream {
/**
* @param in
*/
public Tabs2SpaceInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
// TODO Auto-generated method stub
}
@Override
public int read(byte[] b) throws IOException {
// TODO Auto-generated method stub
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
// TODO Auto-generated method stub
}
}
This class is used to convert tabs to space when the under inpustream is read. Who give some help about this issue? Thanks a lot!.
Because this has the scent of homework about it I won't offer a
fully-worked-out solution, nor even a code sketch. But here are a
few observations and hints that might get you started:
- Are you really sure you want to extend FilterInputStream for
this job? I suspect FilterReader would be a better choice (which
would, of course, involve a different set of read() methods).
- To decide how many spaces a tab should expand to, you'll need
to keep track of the current horizontal position. So: That's one of
the state variables the class requires.
- Keeping track of the horizontal position requires detecting
the ends of line so you know when to reset the position to zero.
- You'll also need to know the positions at which the tabs are
set: Every eight spaces, or every four, or at columns 10,15,35,...
So: That's another state variable.
- For simplicity's sake I'd be inclined to supply the tab positions
(or width) as a constructor parameter; changing the tabs on the fly
could get complicated, and I'd provide for it only if you're pretty sure
you'll need it. So, this state "variable" might actually be a `final'.
- Since a read() call might return only part of a tab's expansion
to spaces, you'll need to keep track of how many spaces are "pending"
before consulting the InputStream (or Reader) again. There's a third
state variable.
- Finally, you should give some thought to the skip() method.
I hope this helps. If you run into trouble, post what you've
managed to write and someone's sure to offer advice.
--
esosman@comcast-dot-net.invalid
"Don't be afraid of work. Make work afraid of you." -- TLM