Presenting a text file as a single block in Java and matching strings in text
How can I get a text file (or XML file) represented as a whole string and search (or match) for a specific string in it?
I created a BufferedReader object:
BufferedReader input = new BufferedReader(new FileReader(aFile));
and then I tried to use the Scanner class with its option to specify different delimiters like:
//Scanner scantext = new Scanner(input);
//Scanner scantext = new Scanner(input).useDelimiter("");
Scanner scantext = new Scanner(input).useDelimiter("\n");
while (scantext.hasNext()) { ... }
Using the Scanner class like this I can either read the text line by line or word by word, but that doesn't help me because sometimes in the text I want to process I have
</review><review>
and I would like to say: if you find " <review>
" anywhere in the text, do something with the next next lines (or piece of text) until you find " </review>
". The problem is that <review>
both </review>
are located in different places in the text, and sometimes they are glued to other text (therefore, empty space as a separator does not help me).
I thought I could use the regex API in Java (Pattern and Matcher classes), but they seem to match a specific string or string, and I want the text to be as one continuous line (at least that was my impression of of what I read about them). Could you please tell me which structures / methods / classes I should be using in this case? Thanks.
source to share
It looks to me like you are trying to work with a structured XML file, and suggest that you take a look into javax.xml.parsers.DocumentBuilder or some other built-in API to parse the document.
source to share
I thought I could use the regex API in Java (Pattern and Matcher classes), but they seem to match a specific string or string, and I want the text to be as one continuous line
Um, is something stopping you from reading an XML file into a String and then working with it using the regex API?
You can read the file into String easily using, for example, FileUtils from Apache Commons IO : see readFileToString(File file, String encoding)
.
source to share