Reputation: 313
I want to get the line of a file, search through that line for specific text, and then return that line plus all the other lines in the file that have the same specific text in them.
I have this so far:
public String searchText(String text, String file)
{
StringBuffer sb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while((line = br.readLine()) != null)
{
while(line.indexOf(text) > 0)
{
sb.append(line);
}
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
It has to be a function I can use when I need it. I hope you guys understand what I want to do, and thanks in advance.
Upvotes: 0
Views: 1434
Reputation: 1000
To be explicit, that inner while-loop is an infinite loop.
Because you are not changing line
or text
within the loop, if the condition is matched once, it will continue to be matched until you exceed the max size of StringBuffer
or run out of memory.
So it's not just that that loop should be an if-statement - it needs to be.
Upvotes: 1
Reputation: 8764
It looks like your code is pretty good, and you're approaching the problem the correct way. You just need a few things to tidy it up, such as separating each line with a \n
newline character, and calling br.close();
when you've finished reading the file. I'm also not sure why you're using a while(line.indexOf(text) > 0)
- it really should be an if
statement.
Depending on how you want to use the lines once you've found them, you might find it nicer to use a ArrayList<String>
and just add()
the matched lines to it (rather than your current StringBuffer
). This would probably be a better solution if you are going to use each line individually when you return from the method.
Upvotes: 2
Reputation: 8230
File
or to turn the
whole File
to a String
.String
's replaceAll
method to replace any Sting
in the File
changed to String
using regex (which is very popular these days) or
just plain String
sUpvotes: 0
Reputation: 2630
your on the correct track except the string returned by the function will be single line so you can not identify the number of lines.
so just add the new line character in final string after every append
Upvotes: 0
Reputation: 68847
There is not really a question, but what I see is that you are not appending a newline character which will cause the search results be on one long line. Add
sb.append('\n');
And change your inner while
to an if
. So the final code should be this:
while((line = br.readLine()) != null)
{
if (line.indexOf(text) > 0)
{
sb.append(line);
sb.append('\n');
}
}
Upvotes: 1