Counts words in a file, outputs results in sorted form : File Commands « File Input Output « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » File Input Output » File CommandsScreenshots 
Counts words in a file, outputs results in sorted form

// : c12:WordCount.java
// Counts words in a file, outputs results in sorted form.
// {Args: WordCount.java}
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

class Counter {
  private int i = 1;

  public int read() {
    return i;
  }

  public void increment() {
    i++;
  }
}

public class WordCount1 {
  private static final String usage = "Usage: \nWordCount file\n"
      "Counts the words in the file and "
      "outputs results in sorted form.";

  private FileReader file;

  private StreamTokenizer st;

  // A TreeMap keeps keys in sorted order:
  private TreeMap counts = new TreeMap();

  public WordCount1(String filenamethrows FileNotFoundException {
    try {
      file = new FileReader(filename);
      st = new StreamTokenizer(new BufferedReader(file));
      st.ordinaryChar('.');
      st.ordinaryChar('-');
    catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    }
  }

  public void dispose() {
    try {
      file.close();
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public void countWords() {
    try {
      while (st.nextToken() != StreamTokenizer.TT_EOF) {
        String s;
        switch (st.ttype) {
        case StreamTokenizer.TT_EOL:
          s = new String("EOL");
          break;
        case StreamTokenizer.TT_NUMBER:
          s = Double.toString(st.nval);
          break;
        case StreamTokenizer.TT_WORD:
          s = st.sval; // Already a String
          break;
        default// single character in ttype
          s = String.valueOf((charst.ttype);
        }
        if (counts.containsKey(s))
          ((Countercounts.get(s)).increment();
        else
          counts.put(s, new Counter());
      }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public Collection values() {
    return counts.values();
  }

  public Set keySet() {
    return counts.keySet();
  }

  public Counter getCounter(String s) {
    return (Countercounts.get(s);
  }

  public static void main(String[] argsthrows FileNotFoundException {
    if (args.length == 0) {
      System.out.println(usage);
      System.exit(1);
    }
    WordCount1 wc = new WordCount1(args[0]);
    wc.countWords();
    Iterator keys = wc.keySet().iterator();
    while (keys.hasNext()) {
      String key = (Stringkeys.next();
      System.out.println(key + ": " + wc.getCounter(key).read());
    }
    wc.dispose();
  }
///:~



           
       
Related examples in the same category
1. File Copy in Java
2. Copying a file using channels and buffers
3. Copy files using Java IO APICopy files using Java IO API
4. Mimic the Unix Grep command
5. File concatenation
6. Compress files using the Java ZIP API
7. Delete file using Java IO API
8. Undent - remove leading spaces
9. TeePrintStream tees all PrintStream operations into a file, rather like the UNIX tee(1) command
10. Delete a file from within Java, with error handling
11. DirTree - directory lister, like UNIX ls or DOS and VMS dirDirTree - directory lister, like UNIX ls or DOS and VMS dir
12. Program to empty a directory
13. Report on a file's status in Java
14. Simple directory lister
15. Readonly Files
16. List root directoryList root directory
17. Rename a file in Java
18. FNFilter - directory lister using FilenameFilter
19. mkdir examples
20. Program to remove files matching a name in a directory
21. Ls directory lister modified to use FilenameFilterLs directory lister modified to use FilenameFilter
22. Dir Stack Dir Stack
23. Word Count
24. Diff: text file difference utility.Diff: text file difference utility.
25. Count chars in a File
www.ja___v_a2__s_.___c_o___m___ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.