DeaIss
DeaIss

Reputation: 2585

Printing out each line of a text file in Java that only contains a specific String?

I'm a bit of a beginner to OOP and was wondering if I could some help on this issue.

How would I go about writing some code that would read each line of a text file, and then only print out each line of the textfile that contains a certain bit of string.

So, for example, lets imagine I have a example.txt file with the following contents:

OK Print this Line;
OK Print this Line;
NO Do not Print this Line;
OK Print this Line;
NO Do not Print this Line;

Is there anyway to get Java to print out only the lines with the string "OK" in it, and do so in a similar format? (So with newline breaks). So I would want Java to print this out:

OK Print this Line;
OK Print this Line;
OK Print this Line;

I've been scouring the internet and trying to think of some ways to do this, but I'm really stuck. Is it possible to do this?

Thanks in advance - if you need any more information, please feel free to ask.

Upvotes: 2

Views: 3624

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You will want to break the problem down into steps. For instance:

  • Figure out how to read each line of text in a file. A Scanner object will work nicely for this and you can find the Scanner API at the link I've provided. Look at using a while loop, Scanner's hasNextLine() and nextLine() method to get you going.
  • Figure out how to see if the String obtained above contains "OK". There's a nice String method that the String API will help you with.
  • Figure out how to print the line if it passes the above test. An if block will help here. I think that you already know how to use System.out.println(...)
  • When done, dispose of the Scanner, tidy up...
  • And voilà, there it is!

Upvotes: 2

Related Questions