Finding words in a txt file!

Hi guys,
I have to write a program that opens a .txt file and looks for a specific word in the file and then prints out the entire line that word appears in. I have to use a String Tokenizer? I don't know how to write the program. All I have so far is a program that prints the entire txt document (or each line). I think String Tokenizer is involved in here somewhere but I don't know how to use it.
import java.io.FileReader;
import java.util.StringTokenizer;
import java.io.*;
public class Find
     public static void main (String[] args) throws IOException
          String line;
          String name;
          String file="find.txt";
          StringTokenizer tokenizer;
          FileReader x = new FileReader (file);
          BufferedReader inFile = new BufferedReader (x);
          line = inFile.readLine();
          while (line != null)
               tokenizer = new StringTokenizer (line);
word = tokenizer.nextToken("word");
               System.out.println (line + "\n");
               line = inFile.readLine();
          inFile.close();
The text file Find.txt just has a few lines of text in it.
I want to make it so that I can look for a specific word in the text file and the resulting printout will be the entire line that the word appears in.
Any help would be great! Thanks!

Your first post is very close to what you want:
import java.io.FileReader;
import java.util.StringTokenizer;
import java.io.*;
public class Find
     public static void main (String[] args) throws IOException
     String line;
     String name;
     String file="find.txt";
     StringTokenizer tokenizer;
     FileReader x = new FileReader (file);
     BufferedReader inFile = new BufferedReader (x);
     line = inFile.readLine();
     while (line != null)
          tokenizer = new StringTokenizer (line);
          String word = tokenizer.nextToken();
          if (word.equals("word")) // we are searchig for the String word
               System.out.println ("found it! "+line + "\n");
          line = inFile.readLine();
     inFile.close();
[\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • 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

  • Tagging words through a .txt file

    Hi all,
    We have been looking all over the internet for a script that we can use/buy. But cannot find it anywhere.
    We have a rather large document and an external word list in a .txt file. This list contains words that need to be in the index at the end of the document.
    Instead of filling in a couple of hundred words and linking them by hand, it would be great if there is a script that can handle this.
    We have looked in to Indexmatic2 (http://www.indiscripts.com/post/2011/07/indexmatic-2-public-release-and-user-s-guide ), but this script generates its own index list and does not create links to the original words in the document.
    We have found a script that can create index links from colored words in the document.
    So does anyone know if there is a script floating around that can load an external .txt wordlist and either color or add a character style to words in a document?
    Or even a script that does what we need in 1 go?
    Thanks

    Thedesmodus,
    there is a script by Martin Fischer at www.hilfdirselbst.ch (a swizz-german website) that could fit your needs. You can download it if you choose to be a premium member which requires a small fee. It's written for InDesign CS3 but it should run with CS4 or CS5. I tested it with a small list of words and it ran fine with InDesign CS5.
    http://indesign.hilfdirselbst.ch/text/indexeintrage-mit-unterstichworten-uber-eine-konkord anzdatei-erzeugen.html
    If you prefer a Google translation:
    http://translate.google.de/translate?hl=de&sl=de&tl=en&u=http%3A%2F%2Findesign.hilfdirselb st.ch%2Ftext%2Findexeintrage-mit-unterstichworten-uber-eine-konkordanzdatei-erzeugen.html
    Uwe

  • Find words within a text file

    Hey all.
    I am playing around with the idea of finding a line of text within a text file, by using scanner and some next methods.
    The way I am trying to get it to work is that one enters a string and the program then finds all the lines of text containing that
    user-entered string and then prints them.
    The text file in question contains names of University papers and their room numbers, quantity of students etc.
    Example:
    IBUS212     EALT006     1am     72     AL     LI     
    BMSC241     MCLT102     2     pm     8     AL     COOREY     
    My problem annoyingly enough seems to be that I can't think how one could compare the string entered to the lines of text being
    scanned in the text file.
    My latest go involved what you see in the code, scanning the examdata.txt file for a user-entered course number, using course.next();
    by going with the example above it would be IBUS212. The task was to then to find all of the lines containing that number and print them out using
    println (what I have tried with id and line) as well as the rest of that line eg: EALT006     1am     72     AL     LI .
       public void printCourse()
        try
            String details, input, id, line;
            int count;
            Scanner user = new Scanner(System.in);
            System.out.println();
            System.out.println();
            System.out.println("Please enter your course ID: ");
            input = user.nextLine();
            Scanner course = new Scanner(new File("examdata.txt"));
            course.next();
            course.nextLine();
            id = course.next();
            line = course.nextLine();
            if(input.equals(id))
                System.out.println("Your course times are: "  + id + "and" + line);
            else
              System.out.println("Your course does not exist."); 
            catch(IOException e)
                System.out.print("File failure");
      }Any advice/help/troubleshooting would be greatly appreciated.
    Edited by: AUAN on Aug 13, 2009 9:43 AM
    Edited by: AUAN on Aug 13, 2009 9:44 AM
    Edited by: AUAN on Aug 13, 2009 9:49 AM

    You'll want [to loop while|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html] the course Scanner has a next line and then print the line if it contains the entered text.
    For useful methods you can check the Javadoc of String and Scanner (use your browser search on keywords like 'next' or 'contains' to find them).

  • How to read Chinese word from a TXT file

    File.OpenText() read a TXT File with  Chinese word in   ;but it not show right.
    exam:The TXT File include :中国
     this.Txt1.Text=ofd.File.OpenText().ReadToEnd();
    but it show :��ʹ�ݼƻ��
    How to solve it

    What encoding does the text file use?  Unlike .NET, Silverlight only supports UTF-8 and UTF-16.  File.OpenText() uses UTF-8 by default.
    If the text file is in some other encoding, you can create your own encoding class (that derives from System.Text.Encoding) that can be used to read the text file.
    class MyEncoding : System.Text.Encoding {
    this.Txt1.Text = (new StreamReader(ofd.File.OpenRead(), new MyEncoding())).ReadToEnd();
    Regards,
    Justin Van Patten
    Program Manager
    Common Language Runtime

  • Help finding key characters in txt file

    Hey I have just been trying to code a script that I can use to search through a bunch of rankings (like 1.Jorden 2.Honza 3.Bill 4.Ted etc) and find how many times each player recieved a vote for each ranking.
    So I might end up with, Jorden was voted 1st 9 times, 2nd 3 times and 3rd 0 times.
    The votes are in a text document, here is the script so far:
    public static void printVotes() {
         int count = 0;
         int a = 0;
         File nFile = new File("Sick1.txt");
         FileReader inStr = new FileReader(nFile);
         BufferedReader inBuff = new BufferedReader(inStr);
         for(int i = 1; i < 15; i++) {
              while(a == 0) {
                   String txtName = inBuff.readLine();
                   if(txtName != null) { //txtName holes the line IE if its like this 1.) Honza
                        StringTokenizer placing = new StringTokenizer(txtName, i);
                        StringTokenizer name = new StringTokenizer(txtName, "Honza");
                        if(placing != null && name != null) {
                             count++;
                   } else {
                        System.out.println(count);
                        a = 1;
    Now it is far from perfect (that being the main reason it does'nt work) but my key question is:
    what is the best way to check how many lines in the .txt document contain the int i (from the for loop) and a givin name (eg "Honza")?

    Your logic needs to look like this:
    for (each line)
       split the line into the rank and name;
       Increment the count for the name/rank pair.
    }I would use a Map to store the rank counts for each name found.

  • Counting Lines/Char/Words in a txt file

    I created this method that counts the mount of lines/words/ and char in a file. But for somereason, its not working correctly. Its giving me numbers that are a little off.
         // Method countLineWordChar counts the number of lines, words, and chars, in
         // a file given as a parameter. This method returns an array of intergers. In
         // the array, the first position is the amount of lines, the second posistion
         // is the amount of words, and the third is the amount of chars.
         public static int[] countLineWordChar(File f)
              int[] countInfo = new int[3];
              int lineCount = 0;
              int wordCount = 0;
              int charCount = 0;
              try
                   FileReader fr = new FileReader(f);
                   StreamTokenizer st = new StreamTokenizer(fr);
                   st.eolIsSignificant(true);
                   while(st.nextToken() != StreamTokenizer.TT_EOF)
                        switch(st.ttype)
                             case StreamTokenizer.TT_WORD:
                             wordCount++;
                             String wordRead = st.sval;
                             charCount += wordRead.length();
                             break;
                             case StreamTokenizer.TT_EOL:
                             lineCount++;
                             break;
                             default:
                             break;
              catch (FileNotFoundException fnfe)
                   UserInterface.showFileNotFoundError();
              catch (IOException ioe)
                   JOptionPane.showMessageDialog(null, ioe.toString(), "Error",
                   JOptionPane.ERROR_MESSAGE);
              countInfo[0] = lineCount;
              countInfo[1] = wordCount;
              countInfo[2] = charCount;
              return countInfo;
         // Based on the countLineWordChar method, returns the amount of lines.
         public static int getLineCount(int[] countInfo)
              return countInfo[0];
         // Based on the countLineWordChar method, returns the amount of words.
         public static int getWordCount(int[] countInfo)
              return countInfo[1];
         // Based on the countLineWordChar method, returns the amount of chars.
         public static int getCharCount(int[] countInfo)
              return countInfo[2];
         }

    Well, for one thing, you're adding the number of characters in words, not the number of characters overall. Are you sure it's not supposed to be the latter?
    Otherwise, how is it off?
    Basically the way you fix this kind of thing is to add debugging code, then give it a small data sample and watch the debugging messages.
    By the way, returning an array of different kinds of values like that isn't ideal. In this case it's not so bad, because the kinds of values are actually really similar -- they could be viewed as a tuple. But don't make a habit of it. An example of a bad application of this would be if you were returning an array that counted, say, the weight of a ship, the length of its hull, and the distance it travelled in the last year. The alternative is to create a class that encapsulates the data being returned, or to move functionality around so the data isn't being returned at all.

  • Search a txt file

    how can i search for a certain word in a txt file?

    import java.awt.*;
    import java.io.*;
    import hsa.Console;
    public class Duel_Prac
        static Console c = new Console ();
        static BufferedReader file;
        static String f_name;
        static String l_name;
        static String option = "";
        static String filedata;
        static public void main (String[] args) throws IOException
            startup_page ();
            main_menu ();
        static void startup_page ()
            c.clear ();
            c.println ("Prac");
            c.println ();
            c.println ("Before we begin, please provide us with the following information about you: ");
            c.println ();
            c.print ("First Name: ");
            f_name = c.readLine ();
            c.print ("Last Name: ");
            l_name = c.readLine ();
        static void main_menu () throws IOException
            c.clear ();
            c.println ("Prac");
            c.println ();
            c.println ();
            c.println ();
            c.print ("1) shop");
            do
                c.setCursor (3, 1);
                c.print ("What do you want do ? ");
                option = c.readLine ();
                if (option.equals ("1") == true || option.equalsIgnoreCase ("shop") == true)
                    break;
            while (!option.equals ("1") && !option.equalsIgnoreCase ("shop"));
            if (option.equals ("1") == true || option.equalsIgnoreCase ("shop") == true)
                shop ();
        static void shop () throws IOException
            try
                file = new BufferedReader (new FileReader ("Card Data/EP1-EN.masterlist"));
                if ((filedata = file.readLine ()) == null)
                    file.close ();
            catch (IOException e)
                c.println ("Data is corrupt");
            String l = "Light";
            if (filedata.equals (l))
                c.println ("Congratualations, your code is correct");
            else
                c.println ("Too bad, your code has bugs");
    }here is the code. what is wrong with it?

  • Yosemite finder crashes with previewig .txt and other files

    Hello,
    under Yosemite  the Finder crashes with previewig .txt and other files.
    Is this just my problem? Help please.
    Thank you very much.
    Regards.

    Launch the Console application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad and start typing the name.
    Step 1
    For this step, the title of the Console window should be All Messages. If it isn't, select
              SYSTEM LOG QUERIES ▹ All Messages
    from the log list on the left. If you don't see that list, select
              View ▹ Show Log List
    from the menu bar at the top of the screen.
    In the top right corner of the Console window, there's a search box labeled Filter. Initially the words "String Matching" are shown in that box. Enter the name of the crashed application or process. For example, if Safari crashed, you would enter "Safari" (without the quotes.)
    Each message in the log begins with the date and time when it was entered. Select the messages from the time of the last crash, if any. Copy them to the Clipboard by pressing the key combination command-C. Paste into a reply to this message by pressing command-V.
    ☞ The log contains a vast amount of information, almost all of which is irrelevant to solving any particular problem. When posting a log extract, be selective. A few dozen lines are almost always more than enough.
    Please don't indiscriminately dump thousands of lines from the log into this discussion.
    Please don't post screenshots of log messages—post the text.
    ☞ Some private information, such as your name, may appear in the log. Anonymize before posting.
    Step 2
    In the Console window, select
              DIAGNOSTIC AND USAGE INFORMATION ▹ User Diagnostic Reports
    (not Diagnostic and Usage Messages) from the log list on the left. There is a disclosure triangle to the left of the list item. If the triangle is pointing to the right, click it so that it points down. You'll see a list of crash reports. The name of each report starts with the name of the process, and ends with ".crash". Select the most recent report related to the process in question. The contents of the report will appear on the right. Use copy and paste to post the entire contents—the text, not a screenshot.
    I know the report is long, maybe several hundred lines. Please post all of it anyway.
    If you don't see any reports listed, but you know there was a crash, you may have chosen Diagnostic and Usage Messages from the log list. Choose DIAGNOSTIC AND USAGE INFORMATION instead.
    In the interest of privacy, I suggest that, before posting, you edit out the “Anonymous UUID,” a long string of letters, numbers, and dashes in the header of the report, if it’s present (it may not be.)
    Please don’t post other kinds of diagnostic report—they're very long and rarely helpful.

  • Find word in text file and count specific words

    now I'll try to explain what I need to do. I have file.txt file, It looks like:
    John //first line - name
    One
    Three
    Four
    Peter //first line - name
    Two
    Three
    Elisa //first line - name
    One
    Three
    Albert //first line - name
    One
    Three
    Four
    Nicole //first line - name
    Two
    FourSo I have program's code:
    public class Testing {
            public static void main(String args[]) throws Exception {
                Scanner input = new Scanner(System.in);
                System.out.println("Select word from list:");
                System.out.println();
                try {
                    FileReader fr = new FileReader("src/lt/kvk/i3_2/test/List.txt"); // this is list of words, everything all right here
                    BufferedReader br = new BufferedReader(fr);
                    String s;
                    while((s = br.readLine()) != null) {
                        System.out.println(s);
                    fr.close();
                    String stilius = input.nextLine();   // eneter word which I want to count in File.txt
                    BufferedReader bf = new BufferedReader(new FileReader("src/lt/kvk/i3_2/test/File.txt")); // from this file I need to count word which I entered before
                    int counter = 0;               
                    String line;
                    System.out.println("Looking for information");
                    while (( line = bf.readLine()) != null){
                        int indexfound = line.indexOf(stilius);
                        if (indexfound > -1) {
                             counter++;
                    if (counter > 0) {
                        System.out.println("Word are repeated "+ counter + "times");}
                        else {
                        System.out.println("Error...");
                    bf.close();
                catch (IOException e) {
                    System.out.println("Error:" + e.toString());
            }This program counting specific word (entered by keyboard) in file.txt.
    I need to make this program: for ex.: if I enter word: One It must show:
    Word One repeated 3 times by John, Elisa, AlbertAll what I need to elect by who this word repeated. But I don't know really how to make It, maybe LinkedList or I dont know, someone could help me?
    Thank you very much.

    966676 wrote:
    All what I need to elect by who this word repeated. But I don't know really how to make It, maybe LinkedListYou should choose the simplest type fullfilling your needs. In this case I'd go for <tt>HashSet</tt> or <tt>ArrayList</tt>.
    or I dont know, someone could help me?You need to introduce a variable to store the actual name which must be resetted if an empty line is found and then gets assigned the verry next word in the file.
    bye
    TPD

  • I am trying to find out how to assign files with particular extensions to the appropriate software. At the moment when I create a file using Word it is apparently given the extension .docx but Word doesn't recognise its own files. How do I alocate th

    I am trying to find out how to assign files with particular extensions to the appropriate software. At the moment when I create a file using Word it is apparently given the extension .docx but Word doesn't recognise its own files. How do I allocate the extension .docx to Word? There used to be a way of doing it, I think under "Preferences" but I can't seem to find it.

    Still in the same location:
    File > Get Info > Open with (select) > Change All (button)

  • Txt file word count

    Hi,
    I have a txt file with words on it i want to count them.
    is there any command that allows me to do it ?
    Thanks

    Enter the following into the Terminal:
    wc -w
    followed by typing a space, dragging the file into the Terminal window or otherwise entering its path, and pressing Enter.
    (44078)

  • Workflow and/ or script to rename finder items using a .txt or a .csv file as a reference?

    Can someone assist me, I am looking for a workflow and/ or script that would allow me to rename finder items using a .txt or a .csv file as a reference for the new naming convention?

    THANK YOU!!!! 
    I have taken your recommendation and enabled the script menubar item.  I also tweeked the script as you recommended, I will play with both options to see which I prefer.   I thank you again for the quick turn around on this. 
    If I am to understand your comment correctly about placing the .csv file in the same folder as the files to be renamed I should modify the script as such.
    REMOVE:    
                        set csvFile to choose file with prompt "Select the CSV file." of type "public.text"
                        set workingFolder to (choose folder "Select the folder to be processed") as text
                        set fileList to (POSIX path of (files of folder workingFolder whose visible is true and name begins with "untitled"))
    REPLACE WITH:     
                        set csvList to paragraphs of (read "/path/to/csvfile.csv")
                          set fileList to (POSIX path of (files of folder "/pah/to/folder" whose visible is true andname begins with "untitled"))
    After reading this and attempting to modify it I am missing one piece of markup or the arrangement of the markup.
    Please find the modified script with options:
    -- change this to specify the correct csv delimiter
    set splitDelimiter to ","
    -- change this to specify the file name join character
    set recombineDelimiter to "_"
    -- choose the csv file
    set csvFile to choose file with prompt "Select the CSV file." of type "public.text"
    -- choose the folder
    set workingFolder to (choose folder "Select the folder to be processed") as text
    -- csv contents as list
    set csvList to paragraphs of (read csvFile)
    --set csvList to paragraphs of (read "/path/to/csvfile.csv")
    tell application "System Events"
    -- list of files in alphabetical order
         set fileList to (POSIX path of (files of folder workingFolder whose visible is true and name begins with "untitled"))
      -- set fileList to (POSIX path of (files of folder "/path/to/folder" whose visible is true and name begins with "untitled"))
         repeat with i from 1 to count of fileList
    -- get a file from the file list and note its extension
              set currentFile to file (item i of fileList)
              set fileExtension to name extension of currentFile
    -- get a line from the csv list, split it at the delimiter,  and recombine it
              set {oldTID, my text item delimiters} to {my text item delimiters, splitDelimiter}
              set newFileNamePieces to text items of (item i of csvList)
              set my text item delimiters to recombineDelimiter
              set newFileName to newFileNamePieces as text
              set my text item delimiters to oldTID
    -- write the new name back out to the file
              set name of currentFile to (newFileName & "." & fileExtension)
         end repeat
    end tell

  • How do I locate non picture files and location? I'm getting low memory and can't find word,PDF etc

    how do I locate non picture files and location? I'm getting low memory and can't find word,PDF etc

    iPads don't have a filesystem like a computer, Files of that nature must be associated with an App and reside inside that particular App's file space.  So the way to find them is to open the App that opens that file type and look in its file or document list for them.

  • Can I do a find and replace on .cfm files only and not search .html or .txt?

    Hi.  I'm using Dreamweaver CS4.  I would like to do a find and replace through my site with Dreamweaver but I only want it to search through .cfm files.  Currently it is searching through .html and .txt files along with .cfm.  Is there a way to do a find and replace on just .cfm files?
    - Tom

    You can't do it on just one type of file. However, you can do find and replace in selected files. Ctrl-click to select the targeted files in the Files panel, and then choose Selected Files in Site from the Find In drop-down.

Maybe you are looking for