Contents
- ./ClosingStreams.java
- ./ConsoleUsingConsoleDemo.java
- ./ConsoleUsingScannerDemo.java
- ./DataIODemo.java
- ./FileTest.java
- ./ScannerPreventExceptions.java
- ./SystemIOExample.java
- ./SystemIOInClass.java
- ./SystemIOReaderExample.java
- ./SystemIOReaderInClass.java
- ./SystemIOReaderStarter.java
- ./SystemIOStarter.java
./ClosingStreams.java 1/12
[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 reading-related 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/12
[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);
int area = height * width;
System.out.println("The area of your rectangle is " + area + ".");
}
}
./ConsoleUsingScannerDemo.java 3/12
[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/12
[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/12
[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 {
// Can easily change the base directory:
private static final String BASE_DIR = ".";
/**
* @param args
*/
public static void main(String[] args) {
//~~~~ create a few different files: ~~~~
File baseDir = new File(BASE_DIR);
File notAFile = new File("/this/is/not/a/file");
// create a file that represents a file in the current directory
// in 3 different ways:
File f = new File("chicken.data"); // default is current directory
File f2 = new File(baseDir + File.separator + "chicken.data");
File f3 = new File(baseDir, "chicken.data");
System.out.println("Reading file: " + 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();
}
displayInfo(baseDir);
displayInfo(f);
displayInfo(f2);
displayInfo(f3);
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());
}
}
./ScannerPreventExceptions.java 6/12
[top][prev][next]
package examples;
import java.util.Scanner;
public class ScannerPreventExceptions {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a long: ");
while( ! sc.hasNextLong() ) {
System.out.println("Oops, that's not a long.");
System.out.println("Please try again...");
// read in what they incorrectly entered
sc.nextLine();
System.out.print("Enter a long: ");
}
long myLong = sc.nextLong();
System.out.println("You entered " + myLong);
sc.close();
}
}
./SystemIOExample.java 7/12
[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);
}
}
./SystemIOInClass.java 8/12
[top][prev][next]
import java.io.IOException;
/**
* Demonstrating some use of the System.in and System.out objects
*
* @author CSCI209
*
*/
public class SystemIOInClass {
/**
* @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("You entered " + number);
}
}
./SystemIOReaderExample.java 9/12
[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);
}
}
./SystemIOReaderInClass.java 10/12
[top][prev][next]
import java.io.IOException;
/**
* Demonstrating some use of the System.in and System.out objects with the
* BufferedReader class
*
* @author CSCI209
*
*/
public class SystemIOReaderInClass {
/**
* @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: ");
int number = 0;
try {
number = System.in.read();
} catch (IOException e) {
e.printStackTrace();
// This is a failure -- should exit gracefully.
System.exit(0);
}
System.out.println("You entered " + number);
}
}
./SystemIOReaderStarter.java 11/12
[top][prev][next]
import java.io.IOException;
/**
* Demonstrating some use of the System.in and System.out objects with the
* BufferedReader class
*
* @author CSCI209
*
*/
public class SystemIOReaderStarter {
/**
* @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: ");
int number = 0;
try {
number = System.in.read();
} catch (IOException e) {
e.printStackTrace();
// This is a failure -- should exit gracefully.
System.exit(0);
}
System.out.println("You entered " + number);
}
}
./SystemIOStarter.java 12/12
[top][prev][next]
/**
* Demonstrating some use of the System.in and System.out objects.
* Needs to be updated to handle checked exception.
*
* @author CSCI209
*
*/
public class SystemIOStarter {
/**
* @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 = System.in.read();
System.out.println("You entered " + number);
}
}
Generated by GNU Enscript 1.6.5.90.