|
Character Input and Output in Java
Intermediate Topics |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
Reader and Writer classes that
can be used to decorate InputStream and
OutputStream objects
import java.io.*;
/**
* A simple exho application that demonstrates character-based I/O in Java.
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class WriterReaderExample
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args) throws IOException
{
BufferedReader in;
PrintWriter out;
String s;
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
out.print("Enter a word: ");
out.flush();
s = in.readLine();
out.print("\nYou typed: " + s + "\n");
out.flush();
}
}
import java.io.*;
import java.net.*;
/**
* An example that illustrates the flexibility of I/O streams
* in Java
*
* -k To use the keyboard
* -f filename To use a file (e.g., cs.txt)
* -u url To use a URL (e.g., http://www.cs.jmu.edu/common/coursedocs/BernsteinMaterials/javaexamples/iobasics/cs.txt)
*/
public class ReaderExample
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args) throws IOException
{
BufferedReader in;
FileReader fileReader;
InputStreamReader isReader;
PrintWriter out;
String line;
URL url;
in = null;
// Construct the appropriate kind of BufferedReader based
// on the command-line options
if (args[0].equals("-f")) { // Read from a file
fileReader = new FileReader(args[1]);
in = new BufferedReader(fileReader);
} else if (args[0].equals("-u")) { // Read from a URL
url = new URL(args[1]);
isReader = new InputStreamReader(url.openStream());
in = new BufferedReader(isReader);
} else { // Read from the keyboard
isReader = new InputStreamReader(System.in);
in = new BufferedReader(isReader);
}
out = new PrintWriter(System.out);
// Keep reading and printing until EOF
do {
line = in.readLine();
if (line != null) {
out.println(line);
out.flush();
}
} while (line != null);
}
}
import java.io.*;
import java.text.*;
/**
* An example that illustrates the use of the NumberFormat
* class
*/
public class ChoiceFormatExample
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args) throws IOException
{
ChoiceFormat formatter;
double grade;
// The intervals are half-open [low, high)
double[] limits = { 0, 60, 70, 80, 90};
String[] letterGrades = {"F","D","C","B","A"};
String outputString;
// Note that the constuctor is used (unlike NumberFormat)
formatter = new ChoiceFormat(limits, letterGrades);
grade = 82.5;
outputString = formatter.format(grade);
System.out.println("Numeric Grade: "+grade);
System.out.println("Letter Grade: "+outputString);
}
}
import java.io.*;
import java.text.*;
import java.util.Locale;
/**
* An example that illustrates the use of the NumberFormat
* class
*/
public class NumberFormatExample
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args) throws IOException
{
NumberFormat formatter;
String outputString;
// Note that the constuctor is often not used directly
formatter = NumberFormat.getInstance();
// An example similar to %d in printf
formatter.setMinimumIntegerDigits(5);
formatter.setGroupingUsed(false);
outputString = formatter.format(20);
System.out.println(outputString);
// An example similar to %f in printf
formatter.setMinimumIntegerDigits(0);
formatter.setMaximumFractionDigits(2);
formatter.setGroupingUsed(false);
outputString = formatter.format(1052.2891554);
System.out.println(outputString);
// An example that prints currency values
formatter = NumberFormat.getCurrencyInstance();
outputString = formatter.format(1953249.25);
System.out.println(outputString);
// An example that prints currency values in a different locale
formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
outputString = formatter.format(1953249.25);
System.out.println(outputString);
}
}
StringTokenizer
import java.io.*;
import java.util.*;
/**
* An example that illustrates the use of reading from a file
* and using the StringTokenizer class.
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class FacultyRecordTokenizer
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args)
{
BufferedReader in;
FileReader fileReader;
InputStreamReader isReader;
String delimiters, email, line, name, phone;
StringTokenizer tokenizer;
try
{
// Setup the reader and writer
fileReader = new FileReader("cs.txt");
in = new BufferedReader(fileReader);
// Keep reading, tokenizing and processing
while ((line = in.readLine()) != null)
{
tokenizer = new StringTokenizer(line, "\t", false);
while (tokenizer.hasMoreTokens())
{
try
{
name = tokenizer.nextToken();
phone = tokenizer.nextToken();
email = tokenizer.nextToken();
// Do something with the information
}
catch (NoSuchElementException nsee)
{
// Do something when there is a problem
}
}
}
in.close();
}
catch (IOException ioe)
{
System.err.println("IO Problem");
}
}
}
parse___() Methodsimport java.io.*;
import java.util.*;
/**
* An example that illustrates the use of the
* StringTokenizer class
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class ExpressionTokenizer
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args) throws IOException
{
double value;
String token;
StringTokenizer tokenizer;
// Setup the delimiters
if (args.length == 0) {
System.out.println("You didn't enter an expression!");
} else {
tokenizer = new StringTokenizer(args[0],
"+-x/%() \t\n",
true); // Return delimiters
// Tokenize the argument
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
System.out.print(token);
System.out.flush();
// Try to convert the token into a double
try {
value = Double.parseDouble(token);
System.out.print(" is a number");
System.out.flush();
} catch (NumberFormatException nfe) {
System.out.print(" is not a number");
System.out.flush();
}
System.out.println();
}
}
}
}
String.split() and
StringTokenizer:
String
String.split() and
StringTokenizer:
split() uses regular expressions,
StringTokenizer uses a list of delimiterssplit() returns an array,
StringTokenizer is an
iterator
StringTokenizer can return the delimiters
as tokens
StringTokenizer and String.split()
import java.io.*;
import java.util.*;
/**
* An example that illustrates the use of the Scanner class
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class BufferedReaderExample
{
/**
* The entry point of the application
*
* @param args The command-line arguments
* @throws IOException if any line can't be read
*/
public static void main(String[] args) throws IOException
{
BufferedReader in;
double salary;
InputStreamReader isr;
int age, weight;
String line, name, phone;
String[] tokens;
StringTokenizer st;
isr = new InputStreamReader(System.in);
in = new BufferedReader(isr);
System.out.print("Name: ");
name = in.readLine();
System.out.print("Salary: ");
line = in.readLine();
salary = Double.parseDouble(line);
System.out.print("Phone number (###-###-####): ");
phone = in.readLine();
System.out.print("Age Weight (# #): ");
line = in.readLine();
// One way to tokenize: Using the split() method
tokens = line.split(" ");
age = Integer.parseInt(tokens[0]);
weight = Integer.parseInt(tokens[1]);
// Another way to tokenize: Using a StringTokenizer
st = new StringTokenizer(line, " ");
age = Integer.parseInt(st.nextToken());
weight = Integer.parseInt(st.nextToken());
in.close();
}
}