This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with Word Count on a file  RSS feed

 
Chaney Woods
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am very new to java and trying to write a program to count words in a file. The file will be read in command line. Does anyone have any pointers on where to start?
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch, Chaney!
Here's a quick example of reading in a text file (the name of which would be specified as a command line argument when starting the program) one line at a time.When figuring out breaking the input line into words, use of a StringTokenizer would be a simple solution.
 
Avi Abrami
Ranch Hand
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chaney,
In my opinion, you have three choices when it comes to parsing text in java:
  • java.io.StreamTokenizer
  • java.util.StringTokenizer
  • java.util.regex (package)

  • Note that the third option is only available since java version 1.4
    You will find _lots_ of sample code on the Internet for all of the above. As a sample -- just to show you what's available -- I did a search for the words "StreamTokenizer" and "java" (which gave me 10,800 hits). Some of the better ones (in my opinion) were these:
    http://mindprod.com/jglossstreamtokenizer.html
    http://www.cs.umb.edu/~bill/java/jdk1.4/src/java/io/StreamTokenizer.java
    http://www.eli.sdsu.edu/courses/fall97/cs535/notes/javaIO2/javaIO2.html
    http://javaalmanac.com/egs/java.io/ParseJava.html
    http://www.cecm.sfu.ca/~kghare/WAVEFRONT/ThreeD.java
    http://www.jguru.com/faq/view.jsp?EID=7190
    The second and third options work with "String"s (not files), so if you decide to use either (or both) of those options, you will need to get the data from your file to a "String". You need to use the classes in package "java.io" for that. Here are three tutorials about using the classes in package "java.io" (but there are also _lots_ more, of-course ;-)
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    http://home.att.net/~baldwin.rg/Intermediate/Java060.htm
    http://www-106.ibm.com/developerworks/edu/j-javaio-i.html
    I hope this helps you -- and that I have correctly interpreted your question and haven't told you things that you already knew, anyway.
    Good Luck,
    Avi.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!