Search a word inside a file uisng java

Hi all,
I have to write a java program that will search the given word inside all the files in the given directory.Finally it has to display the occurance of the word along with its location...i dono how to start with.Can anybody help me with an idea..Thanks in advance.

Look in the java.io package. The class File represents both flat files and directories.
There's also a class in there with a name like "LineNumberReader". You'll probably find that helpful.
You didn't say what the criteria are for finding a match, for example whether it needs to be a case-insensitive match, or whether it must match the whole word or just the start of the word, etc.
There are a variety of ways you can do text pattern matching, but I'd suggest that you do it in the simplest possible way, which would probably be just to use String.indexOf. Later on if this isn't sufficient, you can move up to regular expressions (see the java.lang.regex package).

Similar Messages

  • Reading a LargeFile and search a word in that File

    Hai every one
    I need help,
    I want to read Large File and i have to search a word from that file.
    It is a Dictionar search means searching a meaning for a perticular given word.
    I used FileReader and BufferReader.
    But i didn't get all the file into BufferReader.
    Please Help me
    I written my code is

    I written my code isIt's not going to work with that code.

  • Reading the excel,word,pdf&ppt files using java

    Hi, I am looking for a java program to read the excel, word, pdf & ppt files...I would like to read files based on keywords match criteria... I would appreciate any help on this...

    Hi,
    Look at:
    http://jakarta.apache.org/poi/index.html
    There you'll find the lib:s you need.
    Good luck,
    Magnus

  • Doing a project on search n update utlity for files in java

    having a simple swing interface to select the files in one folder and then updating the same in another corresponding folder that contains a copy of all the files of previous folder... how to go about it.....

    Hello LW130003,
    Do you mean you have the two issues?
    1. Do you mean that you can’t use the search function in control panel? You can only use the search function by using the shortcut Win+S?
    2. When you open any shortcut, you will receive error message ‘This file does not have a program associated with if for performing this action..’?
    Please take the following steps for troubleshooting:
    1. Create a new account, log on the account and check if the issue still exists in the new account.
    If the issue doesn’t exist in the new account, please refer to the following article to fix a corrupted user profile.
    http://windows.microsoft.com/en-us/windows/fix-corrupted-user-profile#1TC=windows-7
    2. If you have issue in open all shortcut in Windows 8, please refer to the following article to restore the registry.
    http://www.eightforums.com/tutorials/8486-default-file-associations-restore-windows-8-a.html
    Please note: Since the website is not hosted by Microsoft, the link may change without notice. Microsoft does not guarantee the accuracy of this information.
    Please refer to the following KB to back up the registry key before you change the registry.
    http://support.microsoft.com/kb/322756
    Best regards,
    Fangzhou CHEN
    Fangzhou CHEN
    TechNet Community Support

  • How read a particular word in a file using java

    Hi.. friends
    I have one problem with reading contents of a file.
    can u give me the source code
    how to read a data from file
    example.
    ss.txt this file contains following data..
    Another Important thing to remember is that the
    instance variables are created and initialzied.
    now the thing is
    i wanted to find words like.. remember, instance
    from ss.txt
    please help me.
    Thnx..

    Read a data from file:
    public void getFileContents() throws Exception
            BufferedReader rdr =
                    new BufferedReader(
                    new InputStreamReader(
                    new FileInputStream(xmlFileName)));
            System.out.println("Reading from file....:" + xmlFileName);
            StringBuffer contents = new StringBuffer();
            String line = null;
            while((line = rdr.readLine())!= null)
                contents.append(line);
        }

  • How do I search for words inside documents, rather than the title? I have OS 10.9.4 and have lost this feature a few OS updates back.

    Sometimes titles do not match the content. If I have a bunch of files with similar title, i.e. Chapter 1, 2, etc., but I want to find the chapter with the jabberwock in it, I used to be able to type "jabberwock" and it would come up in my search window.  Now it's only finding titles. I have so many files on my puter that it's taking me forever to find important documents.  Where did they hide this feature??? Tearing my hair out.

    Spotlight Alternatives
    EasyFind – Spotlight Replacement
    Find Any File

  • Can I read words from a file in java????

    Hi,
    I need help regarding files.
    I have a file with some text in it(say file 1). I need to replace some particular words in the text(file 1) with the words synonyms which are in another file(file 2).
    I need to write the text after replacing it with its synonyms into a new file. Can anyone suggest a way that i could do it.
    Thanks,
    Grandhirs.

    Hi u can use a string tokenizer for this. See the follwing code for example
    try{
    BufferedReader in = new BufferedReader (new FileReader ("file1.txt"));
    while(in.ready()) {
         String line = in.readLine();
         StringTokenizer st = new StringTokenizer(line);
         while(st.hasMoreTokens()){
              String s = st.nextToken();
         } // End of loop for while(st.hasMoreTokens()
         in.close(); // End of Loop while(in.ready())
            } // end of try
         catch (Exception e)
         System.err.println(e); // Print the exception to warn.

  • How to find a particular word in a file using java

    Program how to find a particular word in a file

    SirivaniG wrote:
    Program how to find a particular word in a fileOkay, I finished it. Now what?

  • Merging Word (RTF) files in java

    Hey,
    I have a requirement to merge several word (or rft) files in java. The files are stored as blobs on the database. I had a look at http://poi.apache.org/hwpf/docoverview.html but that project seems to be parked at the moment. Has anybody any ideas?
    Thanks

    I agree its a bad idea but i was asked to look into
    its possibility.
    Previously it wasn't a problem as it was always one
    word file that was required
    for editing through the browser by the user but now
    they want to basically build a 'master doc' based on
    a bunch of business rules i.e. chose a subset of all
    their templates based on business rules at runtime.
    I pitched the idea of generating XSL:FO and adding
    conditionals around the various templates and then
    generating RTF from this. Storing the XSL:FO on the
    db but they didn't like that as they want to be able
    to add and modify new templates and then store these
    directly on the DB?!?!?!The way to address this is to find out what the real concerns are. Almost all stupid requirements are based upon some concern that is the result of a combination of fear and ignorance.
    So I would suggest you find out what the real concern is and address that specifically in your better design.
    Because the reality is that your solution is actually workable. Whereas the one you are being pushed towards will be very difficult and I fear result in an unmaintable mess.

  • Search finds way too many files

    I'm speaking of the Search field you get in Finder when you press command+f: Other than files in application packages, I have two files that have a certain word in the file name, but Finder's command+f pulls back 98, all of them "regular" documents, like PDFs, Numbers, etc., and all but two do not have that word in the file name but they do have the word within the file. The Search field says "name contains:" -- so can get Finder to find only the file names and ignore those with the word inside the file (without using a third-party application)?

    What? You don't like the fact that the new Spotlight makes it almost impossible to find things by name only and not the metadata content? I don't either, but can only suggest  File a bug report with Apple against this loss of functionality or use a 3rd-party app.
    iMac refurb (27-inch Mid 2011), OS X Mavericks (10.9.4), SL & ML, G4 450 MP w/Leopard, 9.2.2

  • How to replace a line ina text file using java?

    Hi ALL,
    Does anybody know how to replace a line in a text file uisng java.

    use this thing:
    http://doesthatevencompile.com/current-projects/code-sniplets/ASCIIFile.htm
    open the file,
    read its contents, replace the text you need in the contents, set the contents back into the file.
    it takes care of the IO for you.

  • Binary search tree - writing to a file in alphabetic order words from tree

    Hi
    I have written a program that will read a list of words from a file, insert these into a binary search tree, write words from the tree to another file, so that the resulting list contains words in ascending order. My input file Alpha1.txt contains the following contents in the order and format given (one word per line):
    Dawn
    Dave
    Mike
    Beth     
    David
    Gina
    Pat
    Cindy
    Sue
    My program is supposed to be producing an alphabetical list of these words in another file "final.txt".
    Instead it gives me the following list:
    Dave Beth David Gina Cindy Sue Pat Mike Dawn
    This is obviously wrong, right? My correct list in "final.txt" should be
    Beth Cindy Dave David Dawn Gina Mike Pat Sue
    I am not sure what is wrong with my code which I reproduce below:
    import java.io.*;
    import java.util.*;
    //read Java Developer's Almanac from exampledepot.com
    //Read this: http://en.wikipedia.org/wiki/Tree_traversal
    /**preorder(node)
      print node.value
      if node.left  ? null then preorder(node.left)
      if node.right ? null then preorder(node.right)
    public class AlphabeticBinarySortTree
         private static TreeNode root;
         private static TreeNode runner;
         static String[] alphaArray;
         static int alphaCounter;
         private static TreeNode alphaRunner;
         //Inner class
              private static class TreeNode
                   String word;
                   TreeNode left;
                   TreeNode right;
                   int count;
                   public TreeNode(String word)
                        this.word = word;
                        left = null;
                        right = null;
                   public void insertAll(TreeNode newNode)
                        if(newNode.word.compareTo(runner.word) < 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.left == null)
                                  runner.left = newNode;
                                  runner = runner.left;
                             else
                                  insertAll(newNode);
                        else if(newNode.word.compareTo(runner.word) > 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.right == null)
                                  runner.right = newNode;
                                  runner = runner.right;
                             else
                                  insertAll(newNode);
                        else
                             count++;
                   }// end method insertAll
                   // Recursively print words (with counts) in sorted order
                     public static void printInPreOrder(TreeNode root)
                             System.out.println(root.word + " ");
                             if(root.left != null)
                                   printInPreOrder(root.left);
                              if(root.right != null)
                                   printInPreOrder(root.right);
                       } //end method printInPreOrder()
                     //called from inside main
                    public static void arrangeInAscendingOrder(TreeNode root, PrintWriter pWriter)
                             if(root.left != null)
                                   arrangeInAscendingOrder(root.left, pWriter);
                             System.out.println();
                             System.out.println();
                             System.out.println(root.word + " ");
                             pWriter.write(root.word + " ");
                             if(root.right != null)
                                  arrangeInAscendingOrder(root.right, pWriter);
              }//end inner class TreeNode
         public AlphabeticBinarySortTree()
              root = null;
         //belong to the outer class
         public static void main(String[] args)
              System.out.println("This program reads text from a file that it will parse. ");
              System.out.println("In doing so, it will eliminate duplicate strings and ");
              System.out.println("pick up only unique strings.These strings will be in a ");
              System.out.println("stored in alphabetical order in a binary Search tree before they are ");
              System.out.println("written out to another text file in alphabetic order");
              //open the file for reading
              try
                   BufferedReader bReader = new BufferedReader(new FileReader("Alpha1.txt"));
                   String words;
                   int count;
                   //System.out.println("A test to inspect the contents of words: " + words);
                   //System.out.println("Words =" + words);
                   count = 0;
                   //why is there an endless loop when
                   //I use "while(str != null)
                   StringTokenizer st;
                   st = null;
                   //based on http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html
                   while ((words = bReader.readLine()) != null)
                        st = new StringTokenizer(words);
                       while(st.hasMoreTokens())
                            //shiffman.net/teaching/a2z/concordance
                            String token = st.nextToken();
                            System.out.println("Token = " +token);
                            AlphabeticBinarySortTree.initiateInsert(token);
                            //count the number of tokens in the string
                            count++;
                        }//end inner while
                   }//end outer while
                   System.out.println("Here are the contents of your tree:");
                   //System.out.println("before the call to print()");
                   print();
                   System.out.println("the no of words in the file is: " + count);
                   bReader.close();
              }//end of try
              catch(IOException exception)
                   exception.printStackTrace();
                   /**try
                             FileWriter fWriter = new FileWriter("final.txt");
                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                             PrintWriter pWriter = new PrintWriter(bWriter);
                   catch(IOExcepion exception)
                        exception.printStackTrace();
         } // end main here
         //this method belongs to the outer class
         static void initiateInsert(String word)
              //TreeNode is also static by the way
              TreeNode newNode = new TreeNode(word);
              if(root == null)
                   root = newNode;
                   System.out.println("root.word = " + root.word);
                   runner = root;
              else
                   runner.insertAll(newNode);
         // Start the recursive traversing of the tree
            //without the access specifier 'static'
            //I would get the following error message
            //AlphabeticBinarySortTree.java:119: non-static method print() cannot be referenced from a static context
            public static void print()
                //System.out.println("**********AM I INSIDE THE PRINT() METHOD? ********");
               if (root != null)
                    //System.out.println("++++++++ AM I INSIDE THE IF BLOCK OF THE PRINT() METHOD? +++++++");
                    //System.out.println("Inside THE IF BLOCK OF print() BUT BEFORE THE CALL TO printInPreOrder(),root.word = " + root.word);
                  AlphabeticBinarySortTree.TreeNode.printInPreOrder(root);
                  //open the file for writing
                              try
                                             FileWriter fWriter = new FileWriter("final.txt");
                                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                                             PrintWriter pWriter = new PrintWriter(bWriter);
                                             AlphabeticBinarySortTree.TreeNode.arrangeInAscendingOrder(root, pWriter);
                                          pWriter.close();
                              catch(IOException eException)
                                   eException.printStackTrace();
               }//end of if block
            } // end of method print
    }//end outer enclosing class here--------
    All help is highly appreciated. Thanks for your time and consideration.

    You suggest that I do away with the inner class
    then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
    The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug.

  • I need autocomplete  for search for words in a txt. file

    i am not so good in java.
    I have a running code for search in text with a txt. file (from user bluefox815).
    But I need a solution with autocomplete for search for words in a txt. file.
    test_file.txt (Teil des Inhaltes):
    Roboter robots
    Mechatronik mechatronics
    and so on
    Can you help me please.
    Here is the code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    * this program searches for a string in a text file and
    * says which line it found the string on
    public class SearchText implements ActionListener {
    private String filename = "test_file.txt";
    private JFrame frame;
    private JTextField searchField;
    private JButton searchButton;
    private JLabel lineLabel;
    private String searchFor;
    private BufferedReader in;
    public SearchText() {
    frame = new JFrame("SearchText");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    searchField = new JTextField(80);
    searchButton = new JButton("Search");
    // this is used later in our actionPerformed method
    searchButton.setActionCommand("search");
    // this sets the action listener for searchButton, which is the current class
    // because this class implements ActionListener
    searchButton.addActionListener(this);
    lineLabel = new JLabel("nach dem Fachbegriff suchen");
    public void createGUI() {
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
    JPanel bottomPanel = new JPanel();
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    topPanel.add(searchField);
    topPanel.add(searchButton);
    bottomPanel.add(lineLabel);
    mainPanel.add(topPanel);
    mainPanel.add(bottomPanel);
    frame.getContentPane().add(mainPanel);
    frame.pack();
    frame.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    // now we get the action command and if it is search, then it is the button
    if ("search".equals(e.getActionCommand())) {
    searchFor = searchField.getText();
    searchTheText();
    private void searchTheText() {
    // I initialize the buffered reader here so that every time the user searches
    // then the reader will start at the beginning, instead of where it left off last time
    try {
    in = new BufferedReader(new FileReader(new File(filename)));
    } catch (IOException e) {
    String lineContent = null;
    int currentLine = 0;
    // this will be set to true if the string was found
    boolean foundString = false;
    while (true) {
    currentLine++;
    // get a line of text from the file
    try {
    lineContent = in.readLine();
    } catch (IOException e) {
    break;
    // checks to see if the file ended (in.readLine() returns null if the end is reached)
    if (lineContent == null) {
    break;
    if (lineContent.indexOf(searchFor) == -1) {
    continue;
    } else {
    lineLabel.setText(String.valueOf(lineContent));
    foundString = true;
    break;
    if (!foundString)
    lineLabel.setText("Es kann kein Fachbegriff gefunden werden.");
    try {
    in.close();
    } catch (IOException ioe) {
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    new SearchText().createGUI();
    }

    Markus1 wrote:
    But I need a solution with autocomplete for search for words in a txt. file.What is your question? What have you tried so far? What are you having difficulty with?
    Mel

  • Uplod word file from java

    how we upload word file from java web page?? pls is urgent.

    > i not understand. pls explain?
    Ok. Take a look at the Fundamentals-forum where your post is in. If you look at the 30 most recent threads there are more tthen 10 thread about uploading files. A couple of those have some usefull answers which you probably can use.
    It's always a good habit to search a forum first before you post your question.
    Good luck.

  • How to search for text inside multiple pdf file at once in ipad

    Hi
    I am student and i need search a word or subject or sentences on my all pdf files,i have tested some applications like ibook, ipdf, addobe reader, good reader ,....  But couldn't find what i need to have.
    Please kindly help me to find the best application.
    Thanks

    I found an article, that claims PDF Expert does exactly what you are asking.
    Article: http://www.imore.com/pdf-expert-ipad-brings-full-text-search-pdf-library
    PDF Expert: https://itunes.apple.com/us/app/pdf-expert-fill-forms-annotate/id393316844?mt=8

Maybe you are looking for

  • Calculation of Tax Issue from FB60 (Tax Code Issue)

    Dear All, Normally when we purchase or received any services we post following entry. INVOICE VALUE IS 1000 Purchase Ac Dr   1000    To Vendor                   900    T o Tax                         100 But our requirement is that Purchase Ac Dr   1

  • IWork 09 not installing on MacBook but installed on MacBook Pro

    I recently purchased a copy of iWork 09 (family pack) from the Apple store. It installed fine on my MacBook Pro and I can see a new folder called iWork 09 in Applications. But when I try and install iWork 09 on any of my 3 MacBooks, the installer com

  • List in a suscreen ?

    Hi all ! I have a question: I've done several times some lists into dynpro by using "Leave to list processing" in the PBO, which works fine. I'd like to know if it is possible to make a list into a subscreen, because it triggers an error saying that

  • Easy camera not working s200

    i lost my IP lenovo easy camera,waht should i do?thanks. Solved! Go to Solution.

  • Restrictions passcode~reset

    I want to rest my restrictions passcode and I tried watching many youtube videos on how to do so but all of them told me to download icopybot which I don't to do, so is there any way I can reset my restrictions passcode without icopybot.