Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 14 of 14

Thread: Parsing a text file in java

  1. #1
    Junior Member
    Join Date
    Jul 2010
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Angry Parsing a text file in java

    • Create a console application that reads text from a text file taken as a command line parameter and outputs the frequency (count) of the words that occur in the text file
    o For example, the command will be run as “java FreqCounter input.txt”, and the output should be of the form: <word>,count

    I tried it with the following code but the output comes as the first word of the text file and the count as 0. It repeats the same output for the complete file.

    The code is as follows:

    import java.io.*;
    class FreqCounter 
    {
    //Code only reads a file
       public static void main(String args[])
      {
          try{
        // Open the file that is the first 
        // command line parameter
        String nameOfFile = args[0]; 
        String sample="";
        String tokens[] = new String[1000];
        int count;
     
     
        FileInputStream fstream = new FileInputStream(nameOfFile);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
            sample=""+strLine;
     
     
        }
     
           tokens = sample.split(" ");
     
        for (int i=0;i<=tokens.length;i++)
        {
            count=0;
            for(int j=i+1;j<=tokens.length;j++)
            {
              if (tokens[i]==tokens[j])
              {
                  count++;
            }
            System.out.println("Word: "+tokens[i]+","+count);
            }
     
        //Close the input stream
        in.close();
        }
    }
     
    catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }
      }
    }
    Last edited by Json; July 5th, 2010 at 02:57 AM. Reason: Please use the highlight tags


  2. #2
    Member Charlie's Avatar
    Join Date
    Jun 2010
    Location
    Sweden
    Posts
    41
    Thanks
    1
    Thanked 5 Times in 5 Posts

    Default Re: Parsing a text file in java

    Edit: Think I missunderstood the question here, gonna work a bit on it later and work it out. Hope you manage to solve it but if not I'll be trying it in netbeans.

    Edit2: And very unmotivating to stumble across this on the net btw

    import java.io.*;
    class FileRead 
    {
       public static void main(String args[])
      {
          try{
        // Open the file that is the first 
        // command line parameter
        FileInputStream fstream = new FileInputStream("textfile.txt");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
          // Print the content on the console
          System.out.println (strLine);
        }
        //Close the input stream
        in.close();
        }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }
      }
    }

    At least try to make your own one? Otherwise your prof better not have access to google.
    Last edited by Charlie; July 5th, 2010 at 06:40 AM.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Parsing a text file in java

    To count the words, you'll need a way to save the words and associate them with a count. See the classes that implement the Map interface for a tool to do this.

  4. #4
    Junior Member
    Join Date
    Jul 2010
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Parsing a text file in java

    Well Charlie the code that you have quoted is only for opening and reading a Java file that I have also used, now I need to modify it further to parse the file it reads

  5. #5
    Member Charlie's Avatar
    Join Date
    Jun 2010
    Location
    Sweden
    Posts
    41
    Thanks
    1
    Thanked 5 Times in 5 Posts

    Default Re: Parsing a text file in java

    Yes I know, but only modifying text like that isnt very optimal since its frowned upon by faculty. You should really at least change the spacing in the code and/or swap some declarations/variable names or something. Just taking the first code you can google up can be very devastating for your grades I think.

    Anyways since you only need to read lines, Id say a bufferedreader and a fileinputstream should be enough. The readline command is very nice for this, but the datastreamreader or whatnot is something I've never personally used (I think its more about reading from one typ of input to another, and .txt is supported by most readers). Like Norm said you will want to save the value so that the reader knows it's handeled the line in specific, so it can move on. This should be done here

    ...
    while ((strLine = br.readLine()) != null)   {
          // Print the content on the console
          System.out.println (strLine);
        }
    ...

    And I dont know if it is (I mean, does it print the whole txt-file here? Because if it does, the problem is that your code is already "finished" with the .txt file).

    Basically just checking while br.readLine() != null would return a true value all the time, since the br is never really "done" with the line in question. But setting its value to a variable like strLine SHOULD make the bufferedReader think its finished here, and make it move on to the next line.

    Try to set the count++ around this part of the code, and see what happens.

  6. The Following User Says Thank You to Charlie For This Useful Post:

    tccool (July 6th, 2010)

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Parsing a text file in java

    I need to parse the file it reads
    Look at the Scanner and StringTokenizer classes for ways to parse/break up Strings into words.

  8. The Following User Says Thank You to Norm For This Useful Post:

    tccool (July 6th, 2010)

  9. #7
    Junior Member
    Join Date
    Jul 2010
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Thumbs up Re: Parsing a text file in java

    Well i have re designed the code with the use of hash maps and String Tokenizer and its working fine now. Thank you all for your help

  10. #8
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Parsing a text file in java

    Glad you have solved your issue tccool. I have marked this thread as solved.

    In future, you can do this yourself from the 'Thread Tools' menu near the top of the thread.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  11. #9
    Junior Member
    Join Date
    Nov 2010
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Parsing a text file in java

    CAN u post the code..i am trying to do exactly the same..parse..read and get some text data from txt filke

  12. #10
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Parsing a text file in java

    Quote Originally Posted by maliv View Post
    CAN u post the code..
    Boo hoo, that's not what a forum is for. Recommended reading:
    How To Ask Questions The Smart Way

    db
    Last edited by Darryl.Burke; November 16th, 2010 at 05:25 AM.

  13. #11
    Junior Member
    Join Date
    Nov 2010
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Parsing a text file in java

    why? i just want to see and understand the code? what is the forum for? spending my time ???
    adios

  14. #12
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Parsing a text file in java

    Maybe this page from another forum's FAQ will help you understand the principles involved.
    Not A Code Mill at JavaRanch

    db

  15. #13
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Parsing a text file in java

    Here's another page from the same FAQ
    Do Your Own Homework at JavaRanch

    db

  16. #14
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Parsing a text file in java

    Quote Originally Posted by maliv View Post
    CAN u post the code..i am trying to do exactly the same..parse..read and get some text data from txt filke
    There are plenty of examples of this code here on the forums. Please try a Search or check out the 'Similar threads' section at the bottom this thread.

    Also look at our code snippets forum:

    Java Code Snippets and Tutorials - Java Programming Forums

    There is code there for reading a file.

    If you get stuck, please post a new thread and we will take it from there
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

Similar Threads

  1. Code for parsing .c file in java
    By Kakashi in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: March 6th, 2013, 12:51 AM
  2. java program to copy a text file to onother text file
    By francoc in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 23rd, 2010, 03:10 PM
  3. java xml-rpc response parsing to xml
    By kievari in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: November 19th, 2009, 02:36 PM
  4. Input file parsing to insert into DB
    By IDForums in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: September 30th, 2009, 02:29 AM
  5. Java program to reduce spaces between the words in a text file
    By tyolu in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: May 13th, 2009, 07:17 AM

Tags for this Thread