Searching for strings in a txt file

I am writing a program based on the six degrees of seperation theory.
Basically I have been given a (very large) txt file from the imdb with a list of all the films written in it.
The text in the document is written like this:
'Tis Autumn: The Search for Jackie Paris (2006)/Paris, Jackie/Moody, James (IV)/Bogdanovich, Peter/Vera, Billy/Ellison, Harlan/Newman, Barry/Whaley, Frank/Murphy, Mark (X)/Tosches, Nick (I)/Moss, Anne Marie
(Desire) (2006)/Ruggieri, Elio/Micijevic, Irena
.45 (2006)/Dorff, Stephen/Laresca, Vincent/Eddis, Tim/Bergschneider, Conrad/Campbell, Shawn (II)/Macfadyen, Angus/John, Suresh/Munch, Tony/Tyler, Aisha/Augustson, Nola/Greenhalgh, Dawn/Strange, Sarah/Jovovich, Milla/Hawtrey, Kay
10 Items or Less (2006)/Ruiz, Hector Atreyu/Torres, Emiliano (II)/Parsons, Jim (II)/Freeman, Morgan (I)/Pallana, Kumar/Cannavale, Bobby/Nam, Leonardo/Hill, Jonah/Vega, Paz/Echols, Jennifer/Dudek, Anne/Berardi, Alexandra
10 MPH (2006)/Weeks, Hunter/Armstrong, Pat (II)/Caldwell, Josh/Waisman, Alon/Keough, Johnathan F./Weeks, Gannon
10 Tricks (2006)/Cruz, Raymond/Swetland, Paul/Selznick, Albie/Hennings, Sam/Gleason, Richard/Leake, Damien/Skipp, Beth/Ishibashi, Brittany/Thompson, Lea (I)/Jinaro, Jossara/Brink, Molly
1001 Nights (2006)/Wright, Jeffrey (I)
10th & Wolf (2006)/Lee, Tommy (VI)/Renfro, Brad/Ligato, Johnny/De Laurentiis, Igor/Luke Jr., Tony/Mihok, Dash/Garito, Ken/Capodice, John/Dennehy, Brian/Gullion, Jesse/Salvi, Francesco (I)/Cordek, Frank/Marsden, James (I)/Bernard, Aaron/Brennan, Patrick (VII)/O'Rourke, Ben/Gallo, Billy/Heaphy, James/Stragand, Dave/Vellozzi, Sonny/Pistone, Joe (I)/Morse, David (III)/Landis, Pete/Cain, Atticus/Trevelino, Dan/Demme, Larry/Sisto, Frank/Rosenbaum, Paul/Grimaldi, James (I)/Ribisi, Giovanni/Hopper, Dennis/Devon, Tony/Sigismondi, Barry/Kilmer, Val/Marinelli, Sonny/Cacia, Joseph/Rossi, Leo (II)/Tott, Jeffrey/Wawrzyniak, Aaron/Boombotze, Joey/Marie, Corina/Arvie, Michilline/Warren, Lesley Ann/De Laurentiis, Veronica/Moresco, Amanda/Boecker, Margot/Rossi, Rose/Latimore, Meritt/Dunlap, Doreen/Perabo, Piper/Horrell, Nickole/Sonnichsen, Ingrid
11 Minutes Ago (2006)/Irving, Len/Welzbacher, Craig/Michaels, Ian/Dahl, Evan Lee/Gebert, Bob/Juuso, Jeremy/Hope, Trip/Green-Gaber, Renata/Dawn, Turiya/Reneau, Taryn/M
Thats just 2 lines!
what the program will do is take in a name (from a gui) of an actor/actress and find the smallest connection to a famous actor.
So first things first, my idea of thinking is to search the file for K.E.V.I.N. B.A.C.O.N and all his films, and safe them into an array. Then do another search for films from the actor that the user entered at the gui. then find the shortest possible connection to both stars.
my code for the search part of the program
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
public class FileSearch {
     File aFile = new File("cast.06.txt");     
     FileInputStream inFile = null;
     String actor = "surname, forename"; // the person who will be the centre point e.g. kevin.bacon.
       //get the result of the actor from the gui will go here.
     public void openFilm()
          try
              inFile = new FileInputStream(aFile);     
          catch(FileNotFoundException e)
               System.out.println("Error");
}The problem I have is that I can't work out how to search the txt file for a specific string/s and save them into an array. (I'm not sure if this is the best way to go about it or not at this stage).
So whats the best way to search for an actor from that file and save the film title and the year of release?
Hope this makes sense? what I hope the final program will be like is like this http://oracleofbacon.org/

I went away and looked at regular expressions and this is what I came up with
public class NameSearch{
     public static void main(String[] args)
          NameSearch ns = new NameSearch();
          ns.runIt();
     public void runIt()
          java.util.Scanner fileScan = null;
          try{
               fileScan = new java.util.Scanner(new java.io.File("imdb.txt"));
          }catch(java.io.FileNotFoundException e)
               e.printStackTrace();
               System.exit(0);
          String token = null;
          String actor = "Surname, Forename";
//real name will go in actor, left it like that for example
          while(fileScan.hasNext()){
               token = fileScan.next();
               Pattern pattern = Pattern.compile(actor);
               Matcher m = pattern.matcher(token);
               while(m.find())
                    System.out.println(m.start() + m.end());
}This by any means not finished, I'm just trying to get to grips with regualr expressions. But when I run the program it doesn't return anything, from what I've tried to work out is it should return actor x amount of times they appear in the file. But when I run it nothing comes back (the actors name is in the text file) so I'm not too sure what I'm doing wrong, any suggestion please

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

  • How do i search for a string in a txt file using java??

    How do i search for a string in a txt file using java??
    could you please help thanks
    J

    Regular expressinos work just fine, especially when
    searching for patterns. But they seem to be impying
    it's a specific group of characters they're looking
    for, and indexOf() is much faster than a regex.If he's reading from a file, the I/O time will likely swamp any performance hit that regex introduces. I think contains() (or indexOf() if he's not on 5.0 yet) is preferable to regex just because it's simpler. (And in the case of contains(), the name makes for a very clear, direct mapping between your intent and the code that realizes it.)

  • How to read and write a string into a txt.file

    Hi, I am now using BEA Workshop for Weblogic Platform version10. I am using J2EE is my programming language. The problem I encounter is as the above title; how to read and write a string into a txt.file with a specific root directory? Do you have any sample codes to reference?
    I hope someone can answer my question as soon as possible
    Thank you very much.

    Accessing the file system directly from a web app is a bad idea for several reasons. See http://weblogs.java.net/blog/simongbrown/archive/2003/10/file_access_in.html for a great discussion of the topic.
    On Weblogic there seems to be two ways to access files. First, use a File T3 connector from the console. Second, use java.net.URL with the file: protocol. The T3File object has been deprecated and suggests:
    Deprecated in WebLogic Server 6.1. Use java.net.URL.openConnection() instead.
    Edited by: m0smith on Mar 12, 2008 5:18 PM

  • How do I search for a word through multiple files in my directories ??

    Hello everyone
    How do I search for a word through multiple files in my directories ??
    I am guessing one tedious way to do it would be to pass all the file names as command line arguments but I"m sure there exist a much easier and faster way to do it.
    Thanks a lot

    You need to pass only the directory name as parameter and then retrieve the files(recursively throug subdirs or not, however you wish) of that directory.
    There were at least 2 threads yesterday on how to retrieve files from directory, and there are many others in the archive so I leave the search part to you ;)
    HTH
    Mike

  • Steady Stream of "Searching for movie data in the file..." Error Messages

    My iMovie has been crippled by error messages that pop up whenever I try to accomplish anything in iMovie. I always see "Searching for movie data in the file 'healyintro.mov'" for a few minutes, then "The movie file 'healyintro.mov' cannot be found. Without this file, the movie cannot play properly." I cannot actually use iMovie because of these errors.
    I've tried everything from reinstalling iMovie to removing application support files to removing my iMovie Events and iMovie Projects folders to creating a .mov file, calling it healyintro.mov and seeing if that'll shut iMovie up – nothing works.
    Once in a while, iMovie will ask for a different movie file, with the same problem.
    Any ideas?

    I am having the same issue. I don't know what the previous poster means by allowing the system to continue, since I'm prompted with a "Cancel" / "Search" dialog after each missing clip. Slight digression: "Search" is not even the correct term here according to UI guidelines ("Choose" or "Locate" might be better choices given the file picker dialog that results).
    I'm actually using Aperture to relocate my video masters on removable media, which is a very nice feature of Aperture, but completely breaks iMovie unless it's connected. Seems like a pretty major oversight.... can we just have it fail more gracefully here and allow us to work with new stuff without getting hung up on missing movie clips from the past?

  • How to do complex file search for "word" unknown characters "word" .file extension?

    How to do complex file search for "word" unknown characters "word" .file extension?

    Using spotlight in Finder helps. Do you know how to search for files in Finder?

  • Saveindg a String in a .txt-File

    Hello,
    I want to save a String to a .txt-File, that is placed in a certain directory.
    How can I Do that?
    Tank you very much!
    Greeting from cologne!
    Marcel

          * Write text to a file.
         * @param text Text to write.
          * @param fileName Name of file to write to.
          * @throws IOException on error.
         static public void writeText(String text, String fileName) throws IOException {
            if (fileName != null && text != null) {
                BufferedWriter bw = null;
                try {
                    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "ISO-8859-1"));
                    bw.write(text, 0, text.length());
                } finally {
                    if (bw != null) { try { bw.close(); } catch (IOException ioe) { ioe.printStackTrace(System.err); }}
            }//else: input unavailable
        }//writeText()Please read D:\docs\JavaTutorial\essential\io\index.html

  • Is it possible to search for strings containing spaces and special characters?

    In our RoboHelp project, there are figures with text labels such as Figure 1, Figure 3-2, etc.
    When I search for "Figure 3" I get all pages containing "Figure" and "3", even if I surround it in quotes.  Similarly, searching for "3-2" treats the '-' character as a space and searches for all pages containing '3' or '2'.
    Is there a way to search for strings containing spaces and special characters?

    In that case I think the answer is no if you are using the standard search engine. However I believe that Zoom Search does allow this type of searching. Check out this link for further information.
    http://www.grainge.org/pages/authoring/zoomsearch/zoomsearch.htm
      The RoboColum(n)
      @robocolumn
      Colum McAndrew

  • Searching for string in text files on XP

    Hi,
    At the moment I'm working on a Struts program. The output I get is:
    The requested resource (Invalid path /displayAddProductForum was requested) is not available.Somewhere in my files, I have a line containing /displayAddProductForum that should be displayAddProductForm. As I'm using XP as my development platform, I use the 'Windows Explorer' search facility. And I have noticed this search facility does not look in .java, .jsp and any other file with a non-Microsoft file-extension. So, how do you search for a string in a source file on XP?
    Abel

    sabre150 wrote:
    kajbj wrote:
    sabre150 wrote:
    Abel wrote:
    , I use the 'Windows Explorer' search facility. And I have noticed this search facility does not look in .java, .jsp and any other file with a non-Microsoft file-extension. So, how do you search for a string in a source file on XP? Err.. On my XP it does search though java/jsp files if I tell it to!You mean by modifying the registry?No! Using the right mouse click on a directory to get a context menu -> Search -> (All or part of filename : .java ) and (A word or phrase in the file : blah blah blah) -> Search
    Edit : Errr.. maybe I'm talking rubbish because I have just tested this and it only finds 5 java files of mine that contain the word 'class'! I'm sure it used to work because in my 'Windows' days I frequently used it.
    Edited by: sabre150 on Dec 20, 2007 12:44 PMSounds a bit odd. Search in windows should only search in registered file types and neither jsp nor java are registered types. It's however possible to modify the registry and add extensions (but it's not possible to say search within all types of files, and that sucks)

  • Comparing char in a string to strings in a txt file

    Hi guys, i am dveloping a scrabble application for a project in jvava. Currently, i am trying to work on coding a computer player to play against a human, ive finished all the game logic nd 2 human players can successfully play on the same system.
    My problem is when coming up with the AI logic, i am faced with the problem of how to compare the computer player's letters to the dictionary txt file in order to find the possible words he can play.
    For example, the PC player has the letters A,B,E,G,T,F in his rack, it searches the dictionary and finds words that also contain these characters, so it would return words like AT, BAT, GATE, etc. I have already looke up the Jumble algorithm, but i dont really understand it(im still quite new to java).
    I already have a ditionary class which i put the code below.
    What i want to do now is just to come up with a simple method that takes a string, and compares the chars, and find words that match the char and return them but i dont knw hw to come about it.
    import java.util.Scanner;      
    import java.io.IOException;  
    import java.util.ArrayList;   
    import java.io.*;             
    public class Dictionary
        ArrayList<String> dictionary;
        public Dictionary() throws IOException
            dictionary = new ArrayList<String>();
        public void readInDictionaryWords() throws IOException
            File dictionaryFile = new File("c:/data/dict.txt");    // declare the file
            if( ! dictionaryFile.exists()) {
                System.out.println("*** Error *** \n" +
                                   "Your dictionary file has the wrong name or is " +
                                   "in the wrong directory.  \n" +
                                   "Aborting program...\n\n");
                System.exit( -1);    // Terminate the program
            Scanner inputFile = new Scanner( dictionaryFile);
            while( inputFile.hasNext()) {
                dictionary.add( inputFile.nextLine().toUpperCase() );
        public boolean wordExists( String wordToLookup)
            if( dictionary.contains( wordToLookup)) {
                return true;    // words was found in dictionary
            else {
                return false;   // word was not found in dictionary
        return"";
    }

    Loops...
    You take the first
    then second
    then third
    and etc
    You take the first 2
    the next 2
    the next 2
    etc
    all the way through n characters
    once you have gone through this, then you have to do all possible combinations of characters of 2 through n.
    Here is an implementation of N choose k for k up to 7:
    public class Junk {
      public Junk(){
      public void choose1(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          System.out.println("("+s.charAt(i)+")");
          lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose2(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
              System.out.println("("+s.charAt(i)+", "+s.charAt(j)+")");
              lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose3(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+")");
              lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose4(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              for(int l=k+1; l<s.length(); l++){
                System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+")");
                lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose5(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              for(int l=k+1; l<s.length(); l++){
                for(int m=l+1; m<s.length(); m++){
                  System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+", "+s.charAt(m)+")");
                  lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose6(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              for(int l=k+1; l<s.length(); l++){
                for(int m=l+1; m<s.length(); m++){
                  for(int n=m+1;n<s.length(); n++){
                    System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+", "+s.charAt(m)+", "+s.charAt(n)+")");
                    lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose7(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              for(int l=k+1; l<s.length(); l++){
                for(int m=l+1; m<s.length(); m++){
                  for(int n=m+1; n<s.length(); n++){
                    for(int o=n+1; o<s.length(); o++){
                      System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+", "+s.charAt(m)+", "+s.charAt(n)+", "+s.charAt(o)+")");
                      lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public static void main(String[] args) {
        Junk j = new Junk();
        j.choose7("1234567");
    }I'll leave it to you to integerate the algos into your app appropriately.

  • Replace the text numbers string in a txt file using C++.. Help Me..

    Read a Document and replace the text numbers in a txt file using c++..
    For ex: 
    Before Document: 
    hai hello my daily salary is two thousand and five and your salary is five billion. my age is 
    twenty-five. 
    After Document: 
    hai hello my daily salary is # and your salary is #. my age is #. 
    All the text numbers and i put the # symbol.. 
    I am trying this code: 
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    ifstream myfile_in ("input.txt");
    ofstream myfile_out ("output.txt");
    string line;
    void find_and_replace( string &source, string find, string replace ) {
    size_t j;
    for ( ; (j = source.find( find )) != string::npos ; ) {
    source.replace( j, find.length(), replace );
    myfile_out << source <<endl;
    cout << source << endl;
    int main () {
    if (myfile_in.is_open())
    int i = 0,j;
    //string strcomma ;
    // string strspace ;
    while (! myfile_in.eof() )
    getline (myfile_in,line);
    string strcomma= "two";
    string strspace = "#";
    find_and_replace( line , strcomma , strspace );
    i++;
    myfile_in.close();
    else cout << "Unable to open file(s) ";
    system("PAUSE");
    return 0;
    Please help me.. Give me the correct code..

    Open the file as a RandomAccessFile. Check its length. Declare a byte array as big as its length and do a single read to get the file into RAM.
    Is this a simple text file (bytes)? No problem. If it's really 16-bit chars, use java.nio to first wrap the byte array as a ByteBuffer and then view the ByteBuffer as a CharBuffer.
    Then you're ready for search/replace. Do it as you would in any other language. Be sure to use System.arraycopy() to shove your bytes right (replace bigger than search) or left (replace smaller than search).
    When done, a single write() to the RandomAccessFile will put it all back. As you search/replace, keep track of size. If the final file is smaller than the original, use a setLength() to the new size to avoid extraneous data at the end.

  • Searching for an entry in a file that contains 2 words or more...

    Hey :)
    I created a Binary Search Tree that would hold a list of words located in a .txt file. So, basically, the objective of the program is to search through a typed up document for the words in the search tree, and if the word is found, return it to the user to see.
    I have that part working, but what I'm having trouble with is one of the entries in the file. The entry is "data structure." All the other entries are 1 word, like queue, depth-first, etc...but this one is 2 words. I'm having trouble making it so that the search will detect the 2-word entry, "data structure." How do I go about searching for entries that are 2 or more words in length?
    I have been struggling with this for some time, and I don't know if it's just me, but I'd really like to get this done since this is the only thing I'm having trouble with right now. I thought I could figure this out, but I'm just putting too much time into it, and I need to submit this tomorrow.
    Any help would really be appreciated! :)
    Take care,
    Alex

    Yea, I was thinking of doing that myself. Turning the two words into one word, so it'll end up like, "datastructure," but how do I do that? Would I use the substring method? Or is there something else that I can use to get rid of whitespace. I'll look that up now on google or something, but in the meantime, if anyone can help me out with this, it would be great.
    Just for a reminder, this is my problem :: I need to be able to locate an entry in my document that has 2 words in it. In this case, the entry is, "data structure." How can I go about searching for this 2 word entry? It seems to be a bit more complex than merely searching for one word. Any help you can provide me would be great! :)
    Here's the code for the Binary Search Tree:
    import java.io.*;
    import java.util.*;
    public class KeywordBinarySearchTree
         BinaryNode root;
         //static String[] docWords; // captures each of the words into an array while ignoring punctuation
         public KeywordBinarySearchTree()
              root = null;
         public void preOrderTraversal()
              preOrderTraversal(root);
         public void inOrderTraversal()
              inOrderTraversal(root);
         public Comparable findNode(Comparable node)
              return dataOfNode(findNode(node, root));
         public Comparable dataOfNode(BinaryNode node)
              if (node == null)
                   return null;
              else
                   return node.nodeData;
         public BinaryNode insertInOrder(Comparable iNodeData)
              BinaryNode nodeWalker;   // used to walk through each of the nodes until the appropriate spot
                                            // is found to insert the node of data
              BinaryNode parentNode = new BinaryNode(iNodeData); // represents the new root node after each pass through the tree
              if (root == null) // if it's a brand new tree with no nodes, then insert the new root of the tree
                   root = new BinaryNode(iNodeData);
              else
                   nodeWalker = root; // sets current root of tree to nodeWalker
                   while (nodeWalker != null) // will start its first iteration of the loop at the top of the tree
                        parentNode = nodeWalker;
                        if (iNodeData.compareTo(nodeWalker.nodeData) < 0) // if the data to be inserted is less than the current
                                                                                       // node in the tree
                             nodeWalker = nodeWalker.leftChild;                  // set nodeWalker to the left child of that node
                             System.out.println("INSERT NODE: LEFT CHILD");
                        else
                             nodeWalker = nodeWalker.rightChild;                 // otherwise, set nodeWalker to the right child of that node
                             System.out.println("INSERT NODE: RIGHT CHILD");
                   } // this loop will determine where the node has to travel to get to the appropriate destination. once the nodeWalker
                     // has reached its final stop, the while loop exits into the statements below to insert the new node of data
                   if (iNodeData.compareTo(parentNode.nodeData) < 0)
                        parentNode.leftChild = new BinaryNode(iNodeData);
                        System.out.println("INSERT NODE: PARENT NODE LEFT CHILD");
                   else
                        parentNode.rightChild = new BinaryNode(iNodeData);
                        System.out.println("INSERT NODE: PARENT NODE RIGHT CHILD");
              return parentNode;
         public BinaryNode findNode(Comparable searchNode, BinaryNode bn)
              if (bn == null)
                   return null;
              else
                   while (bn != null)
                        if (searchNode.compareTo(bn.nodeData) < 0)
                             bn = bn.leftChild;
                             //System.out.println("FIND NODE: LEFT CHILD DETECTED");
                        else if (searchNode.compareTo(bn.nodeData) > 0)
                             bn = bn.rightChild;
                             //System.out.println("FIND NODE: RIGHT CHILD DETECTED");
                        else // word has been spotted in the tree!
                             System.out.println(bn.nodeData);
                             return bn;
              return null;
         public void preOrderTraversal(BinaryNode bn)
              if (bn == null)
                   return;
              System.out.println(bn.nodeData);
              preOrderTraversal(bn.leftChild);
              preOrderTraversal(bn.rightChild);
         public void inOrderTraversal(BinaryNode bn)
              if (bn == null)
                   return;
              inOrderTraversal(bn.leftChild);
              System.out.println(bn.nodeData);
              inOrderTraversal(bn.rightChild);
    // and then the code after this is the public static void main code, which I posted snippets of above.

  • Search a string with in some file and get the name of file

    i want to search a string in some files that are in a given directory and return the name of file having searched string.I am doing this with grep command as given below
    import java.io.*;
    public class linux_java {
    public static void main(String[] args) {
    try {
    String command = "find . | xargs grep -l Resolv /data2/opt/jakarta-tomcat-4.1.24/webapps/Oa/BOG/*.txt";
    final Process process = Runtime.getRuntime().exec(command);
    OutputStream os= process.getOutputStream();
    System.out.println("out put stream= " +os);
    PrintStream stdIn = new PrintStream(new BufferedOutputStream(process.getOutputStream()), true);
    System.out.println("Return code = " + stdIn);
    } catch (Exception e) {
    e.printStackTrace();
    i dont know how to get the name of file that are return by the execution of command through process object. Please send the code for the same

    thanks for your suggestion....
    i change the code but now it is giving error as /usr/bin/find incomplete syntax....but i am giving the right syntax....
    please confirm whether the syntax is correct...
    import java.io.*;
    import java.util.*;
    public class linux_java {
    public static void main(String[] args) {
    try {
    //String command = "ls -alt";
    String command = "find /data2/opt/jakarta-tomcat-4.1.24/webapps/Oa/BOG -type f -exec grep -sl 'Aggarwal' {} \\; 2>/dev/null";
    ///grep -l System test/*java
    System.out.println(" the command is"+command);
    final Process process = Runtime.getRuntime().exec(command);
    InputStream is = process.getErrorStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line="";
    System.out.println(" the BufferedReader is"+br.readLine());
    while ((line = br.readLine()) != null) {
    System.out.println(" the files are"+line);
    } catch (Exception e) {
    e.printStackTrace();
    }

  • How to search a String within a text file ?

    ************** text file ****************
    Good bye good
    bye good bye
    good bye
    good bye good
    bye good
    ************** Input and Output ****************
    Input: good bye
    Output:
    total strings Matched: 5
    whichlinesmatched: 2
    whichlinesmatched: 2
    whichlinesmatched: 3
    whichlinesmatched: 4
    whichlinesmatched: 5
    whichlinesmatched: 0
    whichlinesmatched: 0
    whichlinesmatched: 0
    whichlinesmatched: 0
    whichlinesmatched: 0
    ** but the desired output is 3, and only line 2, 3, 4 matched
    ** Could you please have further help about this? Thank you.
    ************** the codes****************
    import java.io.*;
    public class Tokenize{
    public static void main( String args[] ){
    int maxNumberOfLine = 1000; //the maximium number of line in data file for input
    String fileName = "test"; // file name for data input
    String stringForCount = "good bye"; // specified word for counting
    int totalStringMatched = 0; // number of word matched
    int[] whichLineMatched; // line number for each word matched
    whichLineMatched = new int[maxNumberOfLine];
    // Input string (stringForCount) has been stored in a string array, wordForCompare[]
    // For example: stringForCount = "good bye"
    int stringLength = 2;
    String wordForCompare [] = { "good" , "bye" };
    // wordForCompare[0] = good
    // wordForCompare[1] = bye
    int wordFromFile;
    StreamTokenizer sttkr;
    try{
    FileInputStream inFile = new FileInputStream(fileName); //specifying the file to be opened
    Reader rdr = new BufferedReader(new InputStreamReader(inFile)); //assigned a StreamTokenizer
    sttkr = new StreamTokenizer(rdr);
    sttkr.eolIsSignificant(false);
    System.out.println("Searching for word : " + stringForCount );
    while( (wordFromFile = sttkr.nextToken()) != StreamTokenizer.TT_EOF)
    System.out.println( "going looping through file, token is: " + sttkr.sval );
    if(sttkr.sval.equals(wordForCompare[0])){
    if (stringLength == 1) {
    totalStringMatched++;
    whichLineMatched[totalStringMatched-1]=sttkr.lineno();
    } else {
    for (int p=1; p < stringLength; p++) {
    wordFromFile = sttkr.nextToken();
    System.out.println( sttkr.sval );
    if (!(sttkr.sval.equals(wordForCompare[p])))
    break;
    else if (p==stringLength-1) {
    totalStringMatched++;
    whichLineMatched[totalStringMatched-1] = sttkr.lineno();
    } // end of else
    } // end of for-loop
    } // end of else
    System.out.println( " total strings Matched: " + totalStringMatched );
    } // end of if
    }//end of while for wordFromFile
    for( int i = 0; i < 10; i++)
    System.out.println( "whichlinesmatched: " + whichLineMatched<i> );
    } catch(Exception e) {} //end of try
    }

    A small change to roopa_sree's code, this code fails if there are multiple occurences of the search string in the same line. Make this small change to correct it,import java.io.File;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.StringTokenizer;
    public class WordCounter {
         public static void main(String args[]) throws Exception {
              if(args.length != 1) {
                   System.out.println("Invalid number of arguments!");
                   return;
              String sourcefile = args[0];
              String searchFor = "good bye";
              int searchLength=searchFor.length();
              String thisLine;
              try {
                   BufferedReader bout = new BufferedReader (new FileReader (sourcefile));
                   String ffline = null;
                   int lcnt = 0;
                   int searchCount = 0;
                   while ((ffline = bout.readLine()) != null) {
                        lcnt++;
                        for(int searchIndex=0;searchIndex<ffline.length();) {
                             int index=ffline.indexOf(searchFor,searchIndex);
                             if(index!=-1) {
                                  System.out.println("Line number " + lcnt);
                                  searchCount++;
                                  searchIndex+=index+searchLength;
                             } else {
                                  break;
                   System.out.println("SearchCount = "+searchCount);
              } catch(Exception e) {
                   System.out.println(e);
    }Sudha

Maybe you are looking for

  • Unknown Error when trying to restore backup on iPad

    I'm trying to restore a backup onto my iPad 2, and every time I try to restore it, it does what it should where it starts to load and has the estimated time, etc. But when it finishes it says that there was an unknown error. When I tried to restore i

  • Flash Card Import

    Hello Again Just wondering if anyone else has had an issue with importing from Flash Cards. Lightroom will not import Canon 20D Raw files...it will only let me copy by converting to DNG files. Anyone had this issue...?? Jim

  • Importing from Memory Card (photos taken with Olympus EP1)

    Hi there, I have used a mac pretty much all my life and importing photos from camera/memory cards is like second nature. I have recently started using the Olympus EP1 and transfer my photos using a card reader in my USB drive. Things have been workin

  • Traffic light system sensor

    hi, i'm developing a simulation for a traffic light system. i'm finding problem in traffic lighting system. i gave each traffic light 2 minitus. 120 seconds for re light 50 seconds fro green light and 10 seconds for yellow. i did until the the car mo

  • Expression parameter does not work in 3.1

    When I turn the expression parameter down on an audio channel strip it has no effect. This is not a mapping issue. I mapped the controller to the volume parameter and it worked just fine. I go to the channel strip and change it and it still doesn't w