Results 1 to 8 of 8
  1. #1
    SwapnaNaidu is offline Member
    Join Date
    Nov 2008
    Posts
    5
    Rep Power
    0

    Default Search a word(taken from one file) in another file and give the line as the output

    Each line in file1 is a string.
    In file2 there will be so many lines that contains even Japanese characters in between.
    I am looking for a java program that takes the string in file1 and searches in file2 and gives the line that contains the string to someother file.
    Can anyone help me?

  2. #2
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default

    This is somewhat involved for beginner work, what have you done so far?

    while(secondfile.readline())
    if(firstFile.contains){}

    grossly abbreviated.

    That's not the actual way it is done due to major blocks of code omissions.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  3. #3
    SwapnaNaidu is offline Member
    Join Date
    Nov 2008
    Posts
    5
    Rep Power
    0

    Default

    import java.io.*;
    import java.util.regex.*;
    import java.lang.*;

    class FileReadTest1 {

    public static void main (String[] args) {
    FileReadTest1 f = new FileReadTest1();
    f.readMyFile();
    }

    void readMyFile() {

    DataInputStream dis = null;
    DataInputStream dis1 = null;
    String record = null;
    String in = null;
    String record2 = null;
    int recCount = 0;

    try {

    File f = new File("mydata.txt");
    File f1 = new File("SearchFile.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);

    while ( (record=dis.readLine()) != null ) {
    recCount++;
    System.out.println(recCount + ": " + record);
    try{
    FileInputStream fis1 = new FileInputStream(f1);
    BufferedInputStream bis1 = new BufferedInputStream(fis1);
    dis1 = new DataInputStream(bis1);
    //Pattern myPattern = Pattern.compile("record", CASE_INSENSITIVE);
    while((in=dis1.readLine()) != null)
    {
    // String in = dis1.readLine();
    //if (myPattern.matcher(in).matches("record")) {
    System.out.println(in);
    //}
    }
    }
    catch(IOException e)
    {
    System.out.println("U have go an exception 1 " + e.getMessage());
    }
    }

    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());

    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    } catch (IOException ioe) {
    }
    }
    }
    }
    }


    I want u to suggest how to proceed further search the value in mydata.txt in the file Searchfile.txt and get the lines in separate file.

  4. #4
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Post good start, additional work needed.

    Quote Originally Posted by SwapnaNaidu View Post
    I want u to suggest how to proceed further search the value in mydata.txt in the file Searchfile.txt and get the lines in separate file.
    This is good start, much work needed to place work correctly. Suggest work on code correctness first, then work on actual problem. Comments placed in you code as I straighten the code.

    Much work to do remaining, please work on this some - I have to go to work now on prior commitment.

    Will attempt to do some additional work on this tomorrow morning. See what you can come up with.

    Java Code:
    import java.io.*;// Needed for files.
    import java.util.regex.*;// Very useful for searching.
    import java.lang.*;// This is imported for you, but is okay to leave this import here.
    
    public class FileReadTest1
    {
        // Use some file type with the word Reader in it to read Strings.
        
         BufferedReader  searchFile = null;
         BufferedReader  dataFile   = null;
         
         // Constructor for class.
         FileReadTest1() throws IOException
         {
             File f1 = new File("SearchFile.txt");
             searchFile = new BufferedReader(new InputStreamReader(f1));
             File f2  = new File("mydata.txt")
             dataFile = new BufferedReader(new InputStreamReader(f2));
         }
         public static void main (String[] args)
         {
             try
             {
                FileReadTest1 fileReadTest1 = new FileReadTest1();
                f.readMyFile();
            }
            catch(IOException ioe)
            {
                System.out.println("U have go an exception 1 " + e.getMessage());
                return;// This exits program if file cannot be opened, further work needed here.
            }
         }
    
         void readMyFile() throws IOException
         {
            try 
            {
    
                String record = dataFile.readline();
                if(record != null)
                {
                    String resutlsFileName =  new String("results.txt");//
                    // A place to store results....
                    FileWriter resutlsFile = new FileWriter(resutlsFileName);
                    do
                    {
                        //
                        String nextWordtoSearchfor = searchFile.readline();
                        Pattern myPattern = Pattern.compile(nextWordtoSearchfor, CASE_INSENSITIVE);
                        Matcher matcher = myPattern.matcher(record);//
                        while(matcher.find())
                        {
                            resutlsFile.write(matcher.group());
                        }
                        record = dataFile.readline();
                    }
                    while(record != null);
                }
                else
                {
                    System.out.println("Internal problem with program, contact system administrator.");
                }
            }
            catch(PatternSyntaxException pse)
            {
                System.out.println("A word in the search file conatins a metacharacter..");
                System.out.println(pse.getMessage());;
            }
        }
    }
    I did not do a test compile nor check code in detail. This is simple to "proceed further" ... work remains.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  5. #5
    SwapnaNaidu is offline Member
    Join Date
    Nov 2008
    Posts
    5
    Rep Power
    0

    Default

    Hi Nicholas,
    Thanks for your sugestions.
    I have worked based on your input.
    one more thing I want to make clear is I am looking for the complete line that contains the searched string.
    For Ex:
    If mydata.txt contains Nicholas and if my SearchFile.txt contains "Hi this is Nicholas"
    I want to see "Hi this is Nicholas" in my results.txt file.

    The code I have currently is

    import java.io.*;// Needed for files.
    import java.util.regex.*;// Very useful for searching.
    import java.lang.*;// This is imported for you, but is okay to leave this import here.

    public class FileReadTest1
    {
    // Use some file type with the word Reader in it to read Strings.

    BufferedReader searchFile = null;
    BufferedReader dataFile = null;

    // Constructor for class.
    FileReadTest1() throws IOException
    {
    File f1 = new File("SearchFile.txt");
    searchFile = new BufferedReader(new FileReader(f1));
    File f2 = new File("mydata.txt");
    dataFile = new BufferedReader(new FileReader(f2));
    }
    public static void main (String[] args)
    {
    try
    {
    FileReadTest1 fileReadTest1 = new FileReadTest1();
    fileReadTest1.readMyFile();
    }
    catch(IOException ioe)
    {
    System.out.println("U have go an exception 1 " + ioe.getMessage());
    return;// This exits program if file cannot be opened, further work needed here.
    }
    }

    void readMyFile() throws IOException
    {
    try
    {

    String record = dataFile.readLine();
    if(record != null)
    {
    String resutlsFileName = new String("results.txt");//
    // A place to store results....
    FileWriter resutlsFile = new FileWriter(resutlsFileName);
    String nextWordtoSearchfor;
    while(record != null)
    {
    //
    System.out.println(" hi start");
    //For the first string in mydata.txt it is matching/comparing with all the lines in SearchFile.txt and the nextWordtoSearch will be null.
    //And for the second value in mydata.txt the file is not looping b'coz nextWordtoSearchfor is already null.
    while ((nextWordtoSearchfor = searchFile.readLine()) != null)
    {
    System.out.println(" Search file content " + nextWordtoSearchfor);
    Pattern MyPattern = Pattern.compile(record, Pattern.UNICODE_CASE);
    System.out.println(" mydata file content" + record);
    Matcher matcher = MyPattern.matcher(nextWordtoSearchfor);//
    System.out.println("matcher value " + matcher.find());
    while(matcher.find())
    {
    System.out.println("Hi");// though the value of matcher.find is true , this is not printed
    resutlsFile.write(matcher.group());
    }
    System.out.println("Hi 123");
    }
    record = dataFile.readLine();
    System.out.println(" mydata file content is " + record);
    System.out.println(" my search file content is " + nextWordtoSearchfor); // here the nextWordtoSearchfor always null
    }
    }
    else
    {
    System.out.println("Internal problem with program, contact system administrator.");
    }
    }
    catch(PatternSyntaxException pse)
    {
    System.out.println("A word in the search file conatins a metacharacter..");
    System.out.println(pse.getMessage());;
    }
    }
    }

    The code is compiling correctly.
    It is creating a results.txt file but it is empty.

  6. #6
    SwapnaNaidu is offline Member
    Join Date
    Nov 2008
    Posts
    5
    Rep Power
    0

    Default

    I have tried with my old code also..
    I am able to loop correctly.
    The problem.. I have here is.. though myMatcher.find() is true, it is not giong inside the loop next to it.

    The code I have is (Original with some modifications is also here)

    import java.io.*;
    import java.util.regex.*;
    import java.lang.*;

    class FileReadTest1 {

    public static void main (String[] args) {
    FileReadTest1 f = new FileReadTest1();
    f.readMyFile();
    }

    void readMyFile() {

    DataInputStream dis = null;
    DataInputStream dis1 = null;
    String record = null;
    String in = null;
    String record2 = null;
    int recCount = 0;

    try {

    File f = new File("mydata.txt");
    File f1 = new File("SearchFile.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);

    while ( (record=dis.readLine()) != null ) {
    recCount++;
    System.out.println(recCount + ": " + record);
    FileInputStream fis1 = new FileInputStream(f1);
    BufferedInputStream bis1 = new BufferedInputStream(fis1);
    dis1 = new DataInputStream(bis1);
    System.out.println("Hi: ");
    Pattern myPattern = Pattern.compile(record, Pattern.CASE_INSENSITIVE);
    while((in=dis1.readLine()) != null)
    {

    System.out.println("Inside loop "+ in);
    Matcher myMatcher = myPattern.matcher(in);
    System.out.println("Matcher Value" + myMatcher.find());
    while(myMatcher.find())
    {
    System.out.println("Hi Hello");
    System.out.println("Success:" + myMatcher.group());
    }
    System.out.println("Hi not Success:");
    }
    }

    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());

    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    } catch (IOException ioe) {
    }
    }
    }
    }
    }


    Please let me know,whr I am going wrong..

  7. #7
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Post No 8's here, boss.

    This is good work for first program. I have similar module I worked on in my program. We can read all the words that are being searched for and do HashSet.contains() but that seems to invert the logic - I am still contemplating that. For now I am thinking the approach you are using ( Pattern / Matcher .find() on readline() ) is better. There are additonal improvements that we may be able to find, first we get the program to run.

    This is good accoomplishment for first program, are you studying formally or is this a work you chose to do because it interest you or is being considered as possible employment - which should be discussed in my nutcase post in the Jokes and Funny Things post:Most of pupils not gain valued experience.


    Quote Originally Posted by SwapnaNaidu View Post
    Hi Nick,...If mydata.txt contains Nicholas and if my SearchFile.txt contains "Hi this is Nicholas"
    Java Code:
    import java.io.*;// Needed for files.
    import java.util.regex.*;// Very useful for searching.
    import java.lang.*;// This is imported for you, but is okay to leave this import here.
    /**
    * The code here is a discussion in techincal fora.
    * You may study the code, any use beyond study is 
    * not acceptable under reasonable risk management
    * and would be non-comliance Section 404 Sarbanes-Oxley Act.
    */
    public class FileReadTest1
    {
        // Consistent results file name may be replaced later.
         String resutlsFileName =  new String("results.txt");//
         // Use some file type with the word Reader in it to read Strings.
         BufferedReader  searchFile = null;
         BufferedReader  dataFile   = null;
         // A place to store results....
         FileWriter resultsFile =  null;//
    
         // Constructor for class.
         FileReadTest1() throws IOException
         {
             // File to be examined.
             File f1 = new File("SearchFile.txt");
             searchFile = new BufferedReader(new FileReader(f1));
             // Keyword file.
             File f2  = new File("mydata.txt");
             dataFile = new BufferedReader(new FileReader(f2));
             // Make results of run available after program finishes.
             resultsFile = new FileWriter(resutlsFileName);
         }
         public static void main (String[] args)
         {
             try
             {
                FileReadTest1 fileReadTest1 = new FileReadTest1();
                fileReadTest1.readMyFile();
             }
             catch(IOException ioe)
             {
                 System.out.println("Program has failed to open files needed." + ioe.getMessage());
                 return;// This exits program if file cannot be opened, further work needed here.
             }
             catch(Throwable unspecifiedProblem)
             {
                 System.out.println("An internal error occured, do not continue." + unspecifiedProblem.getMessage());
                 return;// This exits program if file cannot be opened, further work needed here.
             }
         }
    
         void readMyFile() throws IOException
         {
            try
            {
    
                String record = dataFile.readLine();
                if(record != null)
                {
                    int counter = 0x0000;//
                    String nextWordtoSearchfor;
                    while(record != null)
                    {
                        //
                        System.out.println("Good morning, this is SwapnaNaidu. My Hi-Start program finds words in file....");
                        //For the first string in mydata.txt it is matching/comparing with all the lines in SearchFile.txt and the nextWordtoSearch will be null.
                        //And for the second value in mydata.txt the file is not looping b'coz nextWordtoSearchfor is already null.
                        while ((nextWordtoSearchfor = searchFile.readLine()) != null)
                        {
                            System.out.println(" Search file content: " + nextWordtoSearchfor);
                            // We compile pattern to be word we wish to find.
                            Pattern MyPattern = Pattern.compile(nextWordtoSearchfor, Pattern.UNICODE_CASE);
                            // Then we get line from file to be examined.
                            String nextLine = searchFile.readLine(); // [url=http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html#readLine(]BufferedReader (Java 2 Platform SE 5.0)[/url])
                            //
                            if(nextLine != null)
                            {
                                do
                                {
                                    //
                                    Matcher matcher = MyPattern.matcher(nextLine);//
                                    if(matcher.find())
                                    {
                                        // This should print the value of nextLine if matcher.find is true,
                                        // we can then break on inner loop - so as to go to next line in file
                                        // to be examined. The work here is the core of the program and should
                                        // be given careful, tediously detailed examination. Later, we can work
                                        // on implementing Boyer-Moore, Horspool, Raita  from John Burkard.
                                        resutlsFile.write(matcher.group());// Actually, this is results file - write ( targetFile.readLine() ) Which should already be in String record, that's why I have the break two lines away.
                                        // counters are handy, may be commented out for release.
                                        System.out.println("data file content found: " + matcher.group() + " at line number: " + Integer.toString(++counter));
                                        break;// This should break on inner loop, can be break on lable if any reason to do so is discovered.
                                    }
                                    nextLine = searchFile.readLine();// This has to be place here for my loop construct to have correct sequence of operation...
                                }
                                while(nextLine != null);//
                            }
                            else
                            {
                                // program by testing with if's and while, save exceptions for actual exceptions.
                                dataFile.close();
                                searchFile.close();
                                resultsFile.println("early end encountered....");// may be write line or something other than what I have here.
                                resultsFile.close();
                                System.out.println("Encountered blank line in file to be examined...");
                                return;// bail out, program needs further work.
                            }
                        }
                        // Here we announce program termination.
                        System.out.println("Program attained normal termination, who says cat's can't dance?  They are part of the b'coz .... ");
                        // close all files as routine program completion.
                        dataFile.close();
                        searchFile.close();
                        resultsFile.println("Normal end of program....");// may be write line or something other than what I have here.
                        resultsFile.close();
                        return;// bail out, done.
                    }
                 }
                else
                {
                    System.out.println("Internal problem with program, contact system administrator.");
                }
            }
            catch(PatternSyntaxException pse)
            {
                System.out.println("A word in the search file conatins a metacharacter..");
                System.out.println(pse.getMessage());;
            }
        }
    }
    Last edited by Nicholas Jordan; 11-15-2008 at 01:57 AM. Reason: loop logic ....
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  8. #8
    SwapnaNaidu is offline Member
    Join Date
    Nov 2008
    Posts
    5
    Rep Power
    0

    Default

    Hi Nicholas,
    thanks for your help.
    I am working on unix platform.As I have knowledge on Java,I am trying to do it in Java.
    I have the code now in place that can search the word in mydata.txt in the SearchFile.txt and gives the output in results.txt

    import java.io.*;
    import java.util.regex.*;
    import java.lang.*;

    class FileReadTest1 {
    FileWriter results;
    public static void main (String[] args) {
    FileReadTest1 f = new FileReadTest1();
    f.readMyFile();
    }

    void readMyFile() {

    DataInputStream dis = null;
    DataInputStream dis1 = null;
    String record = null;
    String in = null;
    //String record2 = null;
    int recCount = 0;

    try {

    File f = new File("mydata.txt");
    File f1 = new File("SearchFile.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);
    //String resutlsFileName = new String("results.txt");

    results = new FileWriter("results.txt");


    while ( (record=dis.readLine()) != null ) {
    recCount++;
    System.out.println(recCount + ": " + record);
    FileInputStream fis1 = new FileInputStream(f1);
    BufferedInputStream bis1 = new BufferedInputStream(fis1);
    dis1 = new DataInputStream(bis1);
    System.out.println("Hi: ");
    Pattern MyPattern = Pattern.compile(record, Pattern.UNICODE_CASE);
    while((in=dis1.readLine()) != null)
    {

    System.out.println("Inside loop "+ in);
    Matcher matcher = MyPattern.matcher(in);
    //System.out.println("Matcher Value" + matcher.find());
    //results.write("hi how are you");
    if(matcher.find())
    {
    System.out.println("Hi Hello");
    //System.out.println("Success:" + matcher.group());
    results.write(in + System.getProperty( "line.separator" ));

    //break;
    }
    }
    }

    }
    catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());

    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    results.close();
    } catch (IOException ioe) {
    }
    }
    }
    }
    }


    But the problem here is 'As I said already,I have Japanese character in my SearchFile.txt' The results.txt contains some junk characters in place of doublebyte spaces..
    Can you please help me?

Similar Threads

  1. how can i give a file path to java stream ?
    By sheckoo in forum New To Java
    Replies: 2
    Last Post: 11-05-2008, 09:42 AM
  2. File Search
    By Juggler in forum New To Java
    Replies: 2
    Last Post: 07-19-2008, 05:09 PM
  3. Reading a file into java and give it out
    By little_polarbear in forum New To Java
    Replies: 7
    Last Post: 06-05-2008, 11:32 AM
  4. Replies: 13
    Last Post: 01-09-2008, 07:51 AM
  5. Reading in data from file line by line
    By bluekswing in forum New To Java
    Replies: 1
    Last Post: 10-02-2007, 01:19 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •