/home/wpollock1/public_html/restricted/Java2/WordCount.java
// Opens a text file and counts lines, words, and characters.
// Demo of java.io classes. If no file is listed on the command
// line, a File Open dialog is used to select the file. A JOptionPane
// is used to show the output. Note this class has a primitive
// idea of what are words and lines.
//
// Written 4/2011 by Wayne Pollock, Tampa Florida USA
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import static java.lang.Character.isWhitespace;
import static javax.swing.JOptionPane.showMessageDialog;
public class WordCount
{
public static void main ( String [] args ) {
String fileName = null;
// Use the native OS Look and Feel for GUI dialogs:
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch ( Exception e) {}
// Find the name of file to process:
if ( args != null && args.length > 0 )
fileName = args[0];
else
fileName = showFileDialog();
if ( fileName == null || fileName.length() == 0 ) {
showMessageDialog( null, "No filename selected!" );
System.exit(1);
}
// Open file for reading:
Reader file = null;
try {
file = new BufferedReader( new FileReader( fileName ) );
} catch (FileNotFoundException fnfe) {
showMessageDialog( null, "Can't Open file \"" + fileName + "\"!" );
System.exit( 1 );
}
int chars = 0, words = 0, lines = 0; // Initialize counters.
int ch; // The current character read.
boolean inAWord = false; // Only count words when first seen.
char lastChar = 0; // Remember the last character of the file.
try {
while ( (ch = file.read() ) != -1 ) {
++chars;
if ( (char) ch == '\n' ) ++lines;
if ( ! inAWord && ! isWhitespace( (char) ch ) )
++words;
inAWord = ! isWhitespace( (char) ch );
lastChar = (char) ch;
}
file.close();
} catch ( IOException ioe ) {
showMessageDialog( null, "Can't read from file \""
+ fileName + "\"!" );
System.exit( 1 );
}
// Check that last line was counted; Windows text files often
// don't end with a newline:
if ( lastChar != '\n' )
++lines;
// Display results:
showMessageDialog( null,
" Filename: " + fileName + "\nLines: " + lines
+ "\nWords: " + words + "\nCharacters: " + chars );
}
private static String showFileDialog () {
JFileChooser chooser = new JFileChooser();
// Set dialog top open in current directory,
// the same as System.getProperty("user.dir");
// (The default is the user's home directory, typically
// "My Documents" on Windows):
chooser.setCurrentDirectory( new File(".") );
// Only show text files (*.txt and *.java) by default:
FileNameExtensionFilter filter =
new FileNameExtensionFilter( "Text files", "txt", "java" );
chooser.setFileFilter( filter );
int returnVal = chooser.showOpenDialog( null );
// Return selected filename if user clicked "Open", else return null:
if ( returnVal == JFileChooser.APPROVE_OPTION )
return chooser.getSelectedFile().getName();
return null;
}
}