Habbit
September 8th, 2008, 02:25 AM
Hi there,
I'm facing a problem I had not anticipated in the design of "input plugins" for a Java application. This plugins have the general structure of a canRead method that, given an InputStream, tries to guess whether that particular class can parse the whole stream; and methods to actually perform the import.
However, the point is that the canRead method should, if possible, leave the Stream effectively untouched, i.e. in the same position. I have noticed that there is no "seek" method in Java input streams; I had assumed there would be by similarity with .NET streams, but it seems that I am wrong. Googling for it shows nearly nothing, and maybe the solution is obvious because the question was only asked a few times in thousands of results. Some of the solutions I've been offered include the usage of file-input-specific classes such as RandomAccessFile or FileChannel in the java.nio package (that I don't understand too well o_O), but I don't want to limit myself to files, as "memory streams" can be sources for my "plugins" too.
Thus, how could I, given a simple InputStream, know whether or not it can seek (and do it if possible)?. As an example of what I want, this would be the equivalent c# code:
public bool CanRead(Stream is) {
bool retVal;
long startPos = is.CanSeek ? is.Position : -1;
// Check whether this plugin can parse "is" - read from it
if (is.CanSeek)
is.Position = startPos;
return retVal;
}
I'm facing a problem I had not anticipated in the design of "input plugins" for a Java application. This plugins have the general structure of a canRead method that, given an InputStream, tries to guess whether that particular class can parse the whole stream; and methods to actually perform the import.
However, the point is that the canRead method should, if possible, leave the Stream effectively untouched, i.e. in the same position. I have noticed that there is no "seek" method in Java input streams; I had assumed there would be by similarity with .NET streams, but it seems that I am wrong. Googling for it shows nearly nothing, and maybe the solution is obvious because the question was only asked a few times in thousands of results. Some of the solutions I've been offered include the usage of file-input-specific classes such as RandomAccessFile or FileChannel in the java.nio package (that I don't understand too well o_O), but I don't want to limit myself to files, as "memory streams" can be sources for my "plugins" too.
Thus, how could I, given a simple InputStream, know whether or not it can seek (and do it if possible)?. As an example of what I want, this would be the equivalent c# code:
public bool CanRead(Stream is) {
bool retVal;
long startPos = is.CanSeek ? is.Position : -1;
// Check whether this plugin can parse "is" - read from it
if (is.CanSeek)
is.Position = startPos;
return retVal;
}