We help IT Professionals succeed at work.

Search for pattern in file

Sathya75 asked
I have a file with the content...
sagemc_loader.exe 100 10 32768 131072 "SAGE Application" dotproduct.ppc_le -d 2 3

I wanted to check for the pattern dotproduct.ppc_le....if that exist return true else false.

How do I acheive this in java???
I know to read a file I can use....FileReader...but how do i match with the pattern????

Please help....

Watch Question

Read each line of the file as a String. Check for the index of the pattern using String.indexOf() method. If it returns anything other than -1, it means that the pattern is found.

This method will search for a pattern in a file, and returns true if the pattern is found. Otherwise, it returns false.

public boolean find(String fileName, String pattern) throws IOException {
      FileInputStream fis = new FileInputStream(fileName);
      InputStreamReader isr = new InputStreamReader(fis);
      BufferedReader reader = new BufferedReader(isr);
      String line = null;
      while ( (line = reader.readLine()) != null) {
         if (line.indexOf(pattern) != -1) {
            return true; // pattern found
      return false; // pattern not found
hi Sathya ,
 the solution to your problem is in jdk1.4 beta release.
it offers lot flexibility of such type of searching patterns , in a file.
The new packages you have to use

import java.util.regex.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;

i am attaching the sample code for help and implementation.

File Searching

 * Prints out the comments found in a .java file.
import java.util.regex.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;

public class CharBufferExample {
    public static void main(String[] args) throws Exception {
        // Create a pattern to match comments
        Pattern p =
            Pattern.compile("//.*$", Pattern.MULTILINE);
        // Get a Channel for the source file
        File f = new File("test.java");
        FileInputStream fis = new FileInputStream(f);
        FileChannel fc = fis.getChannel();
        // Get a CharBuffer from the source file
        ByteBuffer bb =
            fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
        Charset cs = Charset.forName("8859_1");
        CharsetDecoder cd = cs.newDecoder();
        CharBuffer cb = cd.decode(bb);
        // Run some matches
        Matcher m = p.matcher(cb);
        while (m.find())
            System.out.println("Found comment: "+m.group());

here you replace the search by your pattern dotproduct.ppc_le in the line pattern.compile.

this i think will solve the problem of searching varied patterns in a file.

bhuvneshsharma, please read the guideline below on proposing answers. As your program can only run on JDK1.4, what makes you say that it is the best solution?
Jim CakalicSenior Engineer

If you are searching for a simple substring, yongsing's answer is definitely sufficient. (Don't make the solution any more complex or elegant than is demanded by the problem.)

On the other hand, if you want to search for more complex expressions, and you don't want to wait for JDK 1.4 or can't use JDK 1.4, you might consider one of these regex packages:

Best regards,
Jim Cakalic

25 questions asked, only 6 graded. The last question graded was 2 years ago.
This question is LOCKED with a Proposed Answer.  If it helps you, great, accept it and grade it to close.  If not, reject it and comment as to why or what else is needed.

Few additional experts will join this collaboration effort, once a question has been locked.  Just want to confirm this to you.  If more than one expert helps you, you can always split points or award additional help in a new question, within the same topic area.  If you need help from us, post a zero point question here, and include the link:



Community Support Moderator @ Experts Exchange

ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if still open in seven days.  Please post closing recommendations before that time.

Question(s) below appears to have been abandoned. Your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> You cannot delete a question with comments, special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
Please click the Help Desk link on the left for Member Guidelines, Member Agreement and the Question/Answer process for further information, if needed.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and keep them all current with updates as the collaboration effort continues, to track all your open and locked questions at this site.  If you are an EE Pro user, use the Power Search option to find them.  Anytime you have questions which are LOCKED with a Proposed Answer but does not serve your needs, please reject it and add comments as to why.  In addition, when you do grade the question, if the grade is less than an A, please add a comment as to why.  This helps all involved, as well as future persons who may access this item in the future to seek help.

To view your open questions, please click the following link(s) and keep them all current with updates.

To view your locked questions, please click the following link(s) and evaluate the proposed answer.

------------>  EXPERTS:  Please leave any comments regarding your closing recommendations if this item remains inactive another seven (7) days.  Also, if you are interested in the cleanup effort, please click this link http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643

Moderators will finalize this question if still open in 7 days, by either moving this to the PAQ (Previously Asked Questions) at zero points, deleting it or awarding expert(s) when recommendations are made, or an independent determination can be made.  Expert input is always appreciated to determine the fair outcome.
Thank you everyone.
Moderator @ Experts Exchange

P.S.  For any year 2000 questions, special attention is needed to ensure the first correct response is awarded, since they are not in the comment date order, but rather in Member ID order.

Moondancer, I noticed that you guys are awarding the points automatically to the proposed answer, even though the proposed answer may not be "a specific solution to a problem". It is unfair to the others who had given comments, which could be better answers than the proposed answer.
Jim CakalicSenior Engineer

Did you notice these line from Moondancer's previous posts?


------------>  EXPERTS:  Please leave any comments regarding your closing recommendations

Thanks to you both.  yongsing.... it is CRITICAL that the experts in their respective areas of expertise answer our requests.  We are only a handful of Moderators and are handling @ 176 TAs.  We can't know all subjects as the experts.  

PLEASE guide us by responding to any/all follow ups such as this and tell us who the first best responder was so we can do the fair and right thing.

I spend an average of 15-18 hours each week 7 days a week moderating this site and I am a volunteer.  Your help is appreciated to guide us and help us bring a fair outcome to abandoned questions and to help add value to our PAQ.  We're really trying hard to do the right things here.

Moondancer - EE Moderator
Proposed Answer rejected.

Experts interesting in helping the cleanup effort:

For this question, I suggest you split the points to the three persons who responded.
Jim CakalicSenior Engineer

yongsing responded first with what would appear to be a workable solution. My comment was only intended to direct attention to alternatives, not really a proposed solution to the problem. My recommendation is that yongsing be given the points.

Thanks, Moondancer.
Thanks to you both...
Points for jim_cakalic -> http://www.experts-exchange.com/jsp/qManageQuestion.jsp?qid=20283076
Split finalized.
Moondancer - EE Moderator

Explore More ContentExplore courses, solutions, and other research materials related to this topic.