img
// If no console available, exit.
if(con == null) return;
// Read a string and then display it.
str = con.readLine("Enter a string: ");
con.printf("Here is your string: %s\n", str);
}
}
Here is sample output:
Enter a string: This is a test.
Here is your string: This is a test.
Using Stream I/O
The following example demonstrates several of Java's I/O character stream classes and
methods. This program implements the standard wc (word count) command. The program
has two modes: If no filenames are provided as arguments, the program operates on the
standard input stream. If one or more filenames are specified, the program operates on
each of them.
// A word counting utility.
import java.io.*;
class WordCount
{
public static
int words = 0;
public static
int lines = 0;
public static
int chars = 0;
public static void wc(InputStreamReader isr)
throws IOException {
int c = 0;
boolean lastWhite = true;
String whiteSpace = " \t\n\r";
while ((c = isr.read()) != -1) {
// Count characters
chars++;
// Count lines
if (c == '\n') {
lines++;
}
// Count words by detecting the start of a word
int index = whiteSpace.indexOf(c);
if(index == -1) {
if(lastWhite == true) {
++words;
}
lastWhite = false;
}
else {
lastWhite = true;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home