[antlr-interest] v3 stream input
Sohail Somani
sohail at taggedtype.net
Fri May 26 22:43:59 PDT 2006
On Sat, 2006-05-27 at 07:23 +0200, Martin Probst wrote:
> Hi,
>
> > public class ANTLRInputStream extends ANTLRStringStream {
> >
> > public ANTLRInputStream(InputStream stream) throws IOException
> > {
> > load(stream);
> > }
> >
> > public void load(InputStream istream) throws IOException
> > {
> > BufferedReader br = new BufferedReader(new
> > InputStreamReader(istream));
> ^^^^^^^^^^^^^^^^^^^^^^^^^^
>
> This is the place that is going to bite you some day - you need to
> allow specifying a charset somehow, always taking the system default
> is maybe a bit too optimistic.
Overloaded constructor?
>
> > CharArrayWriter wr = new CharArrayWriter();
> > BufferedWriter bw = new BufferedWriter(wr);
>
> I think you don't need to have a buffered writer around an im memory
> char array, but then again, I'm not that great in the complex
> scientific topic that is reading a simple file in Java ;-)
The only other way I know of would require reallocating a char array in
a loop or converting a Char (using Vector) to a char (as you don't know
the length of the file). Of course, an understanding of the complex
scientific topic that is reading a simple file in Java still escapes
me :)
Maybe this:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.BufferedWriter;
import org.antlr.runtime.ANTLRStringStream;
public class ANTLRInputStream extends ANTLRStringStream {
// Overloaded constructor to allow user to specify a reader
// with a given charset
public ANTLRInputStream(InputStreamReader reader) throws
IOException
{
load(reader);
}
public ANTLRInputStream(InputStream stream) throws IOException
{
load(new InputStreamReader(stream));
}
public void load(InputStreamReader reader) throws IOException
{
BufferedReader br = new BufferedReader(reader);
CharArrayWriter wr = new CharArrayWriter();
BufferedWriter bw = new BufferedWriter(wr);
String line=null;
while((line=br.readLine())!=null)
{
bw.write(line);
bw.newLine(); // TODO: This may not be what you
want
}
bw.close();
data = wr.toCharArray();
}
}
More information about the antlr-interest
mailing list