Question

My application can edit a type of text file called a TDAEntry. Each such entry is based on another type of file that describes its format, called a TDAForm. The very first line in a TDAEntry text file is the name of the form it belongs to, and then the rest of the data (in text form) follows.

For opening such a file now, here is my code, simplified:

InputStream entryInput = new FileInputStream(file);

BufferedReader entryReader = new BufferedReader(
    new InputStreamReader(entryInput)); // PROBLEMATIC #1

String formName = entryReader.readLine();

TDAForm form = new TDAForm(formName);

// create an entry with the right form and the data which follows in entryInput
TDAEntry entry = new TDAEntry(form, entryInput); // PROBLEMATIC #2

Here's the problem. When reading the source code for InputStreamReader, you'll end up reading the code of this class:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/nio/cs/StreamDecoder.java#StreamDecoder.read(char%5B%5D%2Cint%2Cint)

which is buffered, which means that it reads about 8000 bytes ahead. This causes the InputStream at line "Problematic #2" to be empty and in the wrong spot, while I want it to continue as if only the very first line of the file had been read. Inside the constructor of TDAEntry I might want to construct another kind of reader on the stream, or do something else.

One obvious solution is writing a new decoder that doesn't eat up the bytes ahead. But I'm wondering if there's a simpler way to do this. How would you tackle the problem, or do you suggest another programming structure to accomplish the same thing?

Thanks a lot!

Was it helpful?

Solution

Just pass in the reader. it will keep reading where it left off:

TDAEntry entry = new TDAEntry(form, entryReader); 

OTHER TIPS

You could try wrapping your FileInputStream into a BufferedInputStream since the buffered version supports mark() and reset().

If you just want to limit the buffer, you don't need to write your own class. You can use the second constructor, i.e. new BufferedReader(new InputStreamReader(entryInput), 20); to limit the buffer size.

Not that this is necessarily the best way to handle this problem. Basically switching streams in mid-air is quite a bad idea. You could create your own InputStream implementation that reads both the header and the entries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top