Contents
- ./ClosingStreams.java
- ./ConsoleUsingConsoleDemo.java
- ./ConsoleUsingScannerDemo.java
- ./DataIODemo.java
- ./FileTest.java
- ./StandardStreamsExample.java
- ./SystemIOExample.java
- ./SystemIOReaderExample.java
./ClosingStreams.java 1/8
[top][prev][next]
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Demonstrates what happens when you close the outermost connected stream.
*
* @author Sara Sprenkle
*/
public class ClosingStreams {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("myfile.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
br.close();
// calling a method on the fis stream will throw an exception because the stream
// is already closed.
fis.available();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
./ConsoleUsingConsoleDemo.java 2/8
[top][prev][next]
/**
*
*/
package examples;
import java.io.Console;
/**
* A program that demonstrates reading in from the console, using calculating
* the area of a rectangle as the example.
*
* Does not work within an IDE directly--have to run from a terminal.
*
* Note that this class does not have the error checking that
* ConsoleUsingScannerDemo has.
*
* @author Sara Sprenkle
*/
public class ConsoleUsingConsoleDemo {
/**
* @param args
*/
public static void main(String[] args) {
System.out
.println("This program calculates the area of a rectangle.\n");
Console console = System.console();
if (console == null) {
System.err.println("No console.");
System.exit(1);
}
// prompt the user for the width
String widthPrompt = "Please enter the width of a rectangle (as an integer): ";
// check for bad input, read in the integer representing the width
String widthLine = console.readLine(widthPrompt);
int width = Integer.parseInt(widthLine);
// prompt the user for the height
String heightPrompt = "Please enter the height of a rectangle (as an integer): ";
// check for bad input, read in the integer representing the width
String heightLine = console.readLine(heightPrompt);
int height = Integer.parseInt(heightLine);
/*
* scan.close();
*/
int area = height * width;
System.out.println("The area of your rectangle is " + area + ".");
}
}
./ConsoleUsingScannerDemo.java 3/8
[top][prev][next]
package examples;
import java.util.Scanner;
/**
* A program that demonstrates reading in from the console, using calculating
* the area of a rectangle as the example.
*
* @author Sara Sprenkle
*/
public class ConsoleUsingScannerDemo {
/**
* @param args
* not used in this program
*/
public static void main(String[] args) {
System.out
.println("This program calculates the area of a rectangle.\n");
// open the Scanner on the console input, System.in
Scanner scan = new Scanner(System.in);
// Comment this out and enter the text "6 7", for example
scan.useDelimiter("\n"); // breaks up by lines, useful for
// console I/O
// prompt the user for the width
String widthPrompt = "Please enter the width of a rectangle (as an integer): ";
promptAndHandleIntegerInput(scan, widthPrompt);
int width = scan.nextInt();
scan.nextLine(); // eat the new line that the user entered after the
// width was entered (why is there another new
// line?)
// prompt the user for the height
String heightPrompt = "Please enter the height of a rectangle (as an integer): ";
promptAndHandleIntegerInput(scan, heightPrompt);
int length = scan.nextInt();
// don't need to worry about eating the new line because not getting any
// more user input after this.
scan.close();
int area = length * width;
System.out.println("The area of your rectangle is " + area + ".");
}
/**
* Handles prompting for integer input and verifying that we get an integer
* back.
*
* @param scan
* @param prompt
* the prompt used to request the input
*/
private static void promptAndHandleIntegerInput(Scanner scan, String prompt) {
System.out.print(prompt);
// check for bad input, read in the integer representing the width
while (!scan.hasNextInt()) {
handleBadInput(scan, prompt);
}
}
/**
* When the user enters bad input, remove the rest of what's on the line
* from the scanner and print out an error message and a reminder of what
* the input should look like.
*
* @param scan
* where the bad input is coming from
* @param prompt
* a reminder of what we're looking for
*/
public static void handleBadInput(Scanner scan, String prompt) {
// read the bad input (up to the \n, which is what the user
// entered to trigger reading the input)
if (scan.hasNextLine()) {
scan.nextLine();
}
// give an error message and then repeat what we want
System.out.println("Incorrect input.");
System.out.print(prompt);
}
}
./DataIODemo.java 4/8
[top][prev][next]
import java.io.*;
/**
* Demonstrate use of DataInput/OutputStreams with merchandise invoices.
*
* @author CSCI209
*/
public class DataIODemo {
/**
*
* @param args
* - not used in this program
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// I know I don't want this variable to change within this method, so
// made it final
final String FILENAME = "invoice.dat";
// stream to write the data out; file will contain bytes because it's an OutputStream
DataOutputStream out = new DataOutputStream(new FileOutputStream(
FILENAME));
double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
int[] units = { 12, 8, 13, 29, 50 };
String[] descs = { "Java T-shirt", "Java Mug", "Java Beach Towel",
"Java Pin", "Java Key Chain" };
// write the data out
for (int i = 0; i < prices.length; i++) {
out.writeDouble(prices[i]);
out.writeChar('\t');
out.writeInt(units[i]);
out.writeChar('\t');
out.writeChars(descs[i]);
out.writeChar('\n');
}
out.close();
// read the data in again
DataInputStream in = new DataInputStream(new FileInputStream(FILENAME));
double price;
int unit;
StringBuilder desc;
double total = 0.0;
final String lineSepString = System.getProperty("line.separator");
char lineSep = lineSepString.charAt(0);
while (in.available() > 0) {
price = in.readDouble();
in.readChar(); // throws out the tab
unit = in.readInt();
in.readChar(); // throws out the tab
char chr;
desc = new StringBuilder(20);
while ((chr = in.readChar()) != lineSep)
desc.append(chr);
System.out.println("You've ordered " + unit + " units of " + desc
+ " at $" + price);
total = total + unit * price;
}
in.close();
// 2 ways to do the same thing:
System.out.printf("For a TOTAL of $%.2f\n", total);
// OR
System.out.format("For a TOTAL of $%.2f", total);
}
}
./FileTest.java 5/8
[top][prev][next]
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Demonstrate using File objects and FileInputStreams in Java.
*
* @author CSCI209
*
*/
public class FileTest {
/**
* @param args
*/
public static void main(String[] args) {
// String basedir =
// "/Users/sprenkle/Documents/WLU/CS209/";
String basedir = ".";
// create a file that represents the current directory
// File f = new File(basedir + File.separator + "chicken.data");
File f = new File("chicken.data");
System.out.println("File is " + f.getAbsolutePath());
try {
FileInputStream fin = new FileInputStream(f);
while (fin.available() > 0) {
System.out.println(fin.read());
}
/* Consider how we'd write the code if we don't use the available() method:
* When would the loop stop?
* The loop would keep going, waiting for more input. That could be valid code,
* but more often, you probably want to stop looping when you run out of stuff to read,
* like from a file.
*/
/*
while( true ) {
int input = fin.read();
System.out.println(input);
}
*/
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File notAFile = new File("/this/is/not/a/file");
displayInfo(f);
displayInfo(notAFile);
}
/**
* Displays info (if it's a file and if it's a directory) about the given file
*
* @param myFile the file to display information about
*/
private static void displayInfo(File myFile) {
System.out.println(myFile.getAbsolutePath() + " is a file: "
+ myFile.isFile());
System.out.println(myFile.getAbsolutePath() + " is a directory: "
+ myFile.isDirectory());
}
}
./StandardStreamsExample.java 6/8
[top][prev][next]
import java.io.*;
/**
* Demonstrate use of standard error and standard out
*
* (Not using standard Javadoc to show what happens with the output.
*
* Run from the command line different ways:
The standard way, where standard out and standard error are directed to the
terminal:
$ java StandardStreamsExample
This is to standard out 1
This is to standard error 1
This is to standard out 2
This is to standard error 2
Redirecting the output to a file named output:
$ java StandardStreamsExample > out
This is to standard error 1
This is to standard error 2
--> You still see the error messages because they are directed to the
terminal, rather than to a file.
Redirecting both standard out and standard error to their own files:
$ java StandardStreamsExample 1> out 2> err
$ cat out
This is to standard out 1
This is to standard out 2
$ cat err
This is to standard error 1
This is to standard error 2
Redirecting both standard out and standard error to one file:
$ java StandardStreamsExample 1> out 2>&1
$ cat out
This is to standard out 1
This is to standard error 1
This is to standard out 2
This is to standard error 2
*
*
* @author Sara Sprenkle
*/
public class StandardStreamsExample {
/**
*
* @param args
* - not used in this program
*/
public static void main(String[] args) {
System.out.println("This is to standard out 1");
System.err.println("This is to standard error 1");
System.out.println("This is to standard out 2");
System.err.println("This is to standard error 2");
}
}
./SystemIOExample.java 7/8
[top][prev][next]
import java.io.IOException;
/**
* Demonstrating some use of the System.in and System.out objects
*
* @author CSCI209
*
*/
public class SystemIOExample {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Trying out System.out and System.in classes");
System.out.print("Enter an integer: ");
int number = 0;
try {
number = System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("User did not enter a number?");
}
System.out.println("You entered " + number);
}
}
./SystemIOReaderExample.java 8/8
[top][prev][next]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Demonstrating some use of the System.in and System.out objects
* with the BufferedReader class
*
* @author CSCI209
*
*/
public class SystemIOReaderExample {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Trying out System.out and System.in classes, using a BufferedReader");
System.out.print("Enter an integer: ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int number=0;
try {
String line = in.readLine();
number = Integer.valueOf(line);
in.close();
} catch (IOException e) {
e.printStackTrace();
// This is a failure -- should exit gracefully.
System.exit(0);
}
System.out.println("You entered " + number);
}
}
Generated by GNU Enscript 1.6.6.