This answer applied to the original version of the question, where the key was to read the stream only as needed, to match on a String if that String is present. This solution would not meet the requirement to guarantee a fixed memory usage, but it may be advisable to consider whether you found this question and are not bound by this restriction.
If you are bound by a restriction on the use of read-only memory, Java stores arrays of any type on the heap, and as such zeroing, the reference does not free memory in any way; I think that any solution involving arrays in a loop will consume memory on the heap and require GC.
For a simple implementation, there may be a Java 5 Scanner that can accept an InputStream and use java.util.regex.Pattern to search for input can save your attention on implementation details.
Here is an example of a potential implementation:
public boolean streamContainsString(Reader reader, String searchString) throws IOException { Scanner streamScanner = new Scanner(reader); if (streamScanner.findWithinHorizon(searchString, 0) != null) { return true; } else { return false; } }
I am thinking of a regex because it is like a job for Finate State Automaton that starts in its original state, changing the state character by character until it rejects the line (no match) or falls into accept state.
I think this is probably the most efficient matching logic you could use, and how you organize the reading of information can be separated from the matching logic to tune performance.
This is also how regular expressions work.
brabster May 10, '09 at 21:53 2009-05-10 21:53
source share