27
November 10, 2005 Input and Output 1 of 26 Input and Output • String I/O • Console I/O • File I/O

November 10, 2005Input and Output1 of 26 Input and Output String I/O Console I/O File I/O

Embed Size (px)

Citation preview

November 10, 2005Input and Output 1 of 26

Input and Output

• String I/O

• Console I/O

• File I/O

November 10, 2005Input and Output 2 of 26

Strings

• We’ve used strings before, but usually as literals– e.g. new Frame(“xterm”);

• We can use strings like this, but they are really objects– String s = new String();

• Strings define some very useful methods– substring(int start, int end)

• Returns a substring made up of the characters from index start to index end-1 in the original string

– equals(String otherString)• Checks to see if two strings are the same character

for character• Use this instead of the == operator, which checks to

see if the memory addresses are the same– toUpperCase()

• Makes all characters upper case

– See the javadocs for more useful methods

October 25, 2005

November 10, 2005Input and Output 3 of 26

String Concatenation

• We often want to stick one string on the end of another

• This is known as concatenation– since it is used so often, java lets us use the +

operator rather than call a method

String first = “Joe”;String last = “Somebody”;System.out.println(first + last);

• This will print out JoeSomebody– let’s fix that:

System.out.println(first + “ “ + last);

• Now it will print out Joe Somebody

November 10, 2005Input and Output 4 of 26

Comparing Strings

• Let’s see how to compare two stringsString student = “Sara”;String other_student = “sara”;other_student = student.toLowerCase();

• student == other_student

returns false

• What’s going on here?– the == operator is checking memory addresses– we want to compare the characters that make up the

strings

• Use equals(String other)!• student.equals(other_student)

returns true

November 10, 2005Input and Output 5 of 26

Console I/O

• Pre-GUI

• Interface for communication with computer– Type commands– Receive output as text

• No clicking required!– Edit code– Compile– Run programs– Data entry

• Keyboard/Console Input– Data typed into a console window by user

• Console Output– Data displayed in window by program

• Collectively referred to as Console I/O

November 10, 2005Input and Output 6 of 26

Console Output in Java

• Magic!

• Platform specific, hidden by Java

• Console window represented by an Object– System.out– Public instance variable in System class

• Instance of PrintStream class• Never throws exceptions!

– Always open, always ready for output– Part of Java’s policy: “Write Once, Run Anywhere”

November 10, 2005Input and Output 7 of 26

• System.out.print– Writes a message to the console– System.out.print(“CS is neat!”);

• Message will appear on screen with prompt directly to the right

System.out.printing

That looks ugly! How can we fix it?

Java fixes it for us! Use System.out.println

instead!

November 10, 2005Input and Output 8 of 26

Prettier printing

• Use System.out.println!

• System.out.println(“CS is neat!”);• Java will automatically add a newline character (‘\n’)

at the end of the message:

• You can use the newline character too– Insert ‘\n’ wherever you want the line to breakSystem.out.print(“CS\nis\nneat!\n”);– Java will add three newline characters– Text prints on four lines:

CS15isneat!

– System.out.print(“CS15 is neat!\nYeah!”);

– Prints out:CS15 is neat!Yeah!

November 10, 2005Input and Output 9 of 26

More printing

• We’re tired of printing Strings– Can we print other types of values?– Of course!

• These methods can take different types of arguments– booleans, ints, doubles, or Objects

import java.awt.geom.*;public class OutputDemo {public OutputDemo() { System.out.println(“Begin demo:”); System.out.print(“Print an int: ”); System.out.println(12); System.out.println(“Two booleans:”); System.out.println(true); System.out.println(false); System.out.print(“A double: ”); System.out.println(Math.PI); Ellipse2D.Double e = new

Ellipse2D.Double(); e.setFrame(30, 40, 50, 60); System.out.println(“An object:”); System.out.println(e);}

public static void main(String[] args) {OutputDemo app = new OutputDemo();

}}

November 10, 2005Input and Output 10 of 26

OutputDemo console output

Begin demo:

Print an int: 12

Two booleans:

True

False

A double: 3.141592653589793

An object:

java.awt.geom.Ellipse2D$Double@e53108

• It may seem like printing out Objects isn’t very useful– most of the time it’s just a (seemingly) random string of letters

and numbers– but... you can use it to check for null!

• The next time you get a NullPointerException– try printing out the object you think might be null– the next time you run your program, check what gets printed

out– if it says “null” right before the exception is thrown, you

know that you need to initialize that object

November 10, 2005Input and Output 11 of 26

Console Input in Java

• We have seen how to WRITE to the console using Java built-in commands

• What if we want our program to be able to READ user input from a console?– You guessed it!– System.in

• Public instance variable in System class• Just like System.out• Always ready to use• Requires no initialization in code you write

• There are a few differences…

November 10, 2005Input and Output 12 of 26

Scanners

• Instead of reading directly from System.in, use a Scanner– Always have to tell the Scanner what to read– Instantiate it with a reference to read from System.in

java.util.Scanner scanner = new

java.util.Scanner(System.in);

• What does the Scanner do, and why do I need one?– Breaks down input into manageable units, called

tokens• Instead of drinking from the fire hose, we get passed

nicely packaged bottles of water

Scanner scanner = new Scanner(System.in);

String userInput = scanner.nextLine();

• nextLine() grabs everything typed into the console until the user enters a carriage return (hits the “Enter” key)– Tokens are the size of a line input and labeled String

November 10, 2005Input and Output 13 of 26

Application of Console I/O

• We can write other data types, not just Strings– We can also read them!

import java.util.*;

public class EchoAge {

public EchoAge() {

System.out.print(“Enter your name: “);

Scanner scan = new Scanner(System.in);

String name = scan.nextLine();

System.out.print(“Enter your age: “);

int age = scan.nextInt();

System.out.println(name + “ is “ + age + “ years old.”);

}

public static void main(String[] args) {

EchoAge app = new EchoAge();

}

}

November 10, 2005Input and Output 14 of 26

Sample run and more methods

If Mike runs this program, the console would show:

$ java EchoAgeEnter your name: Mike

Enter your age: 20

Mike is 20 years old.

$

• What else can Scanners read?

To read in a: Use Scanner method

boolean boolean nextBoolean()

double double nextDouble()

float float nextFloat()

int int nextInt()

long long nextLong()

short short nextShort()

String (appearing in the next line, up to ‘\n’)

String nextLine()

String (appearing in the line up to next ‘ ‘, ‘\t’, ‘\n’)

String next()

November 10, 2005Input and Output 15 of 26

Scanner Exceptions

• InputMismatchException– Thrown by all nextType() methods– Token cannot be translated into a valid value of

specified type– Scanner does not advance to the next token, so

that this token can still be retrieved

• Handling this Exception– Prevent it

• Test next token by using a hasNextType() method• Doesn’t advance the token, just checks and verifies

type of next token– boolean hasNextBoolean()– boolean hasNextDouble()– boolean hasNextFloat()– boolean hasNextInt()– boolean hasNextLong()– boolean hasNextShort()– boolean hasNextLine()– Etc…– See the javadocs for more info about Scanner

methods!– Catch it

• Handle the Exception once you catch it

November 10, 2005Input and Output 16 of 26

File Overview

• What is a file?– a collection of data with a name– allows for long-term storage– has a name associated with it so that it can be found

later

• Motivation:– often when working with computers we would like to

be able to save what we’re working on and come back to it later

– would like to be able to save settings and options– would like to be able to transfer data between

computers

November 10, 2005Input and Output 17 of 26

File Representation

• From the point of view of an object-oriented programmer, a file is an object with properties and methods

• Properties include, among other things:– it’s location in long-term memory (called the path)

• e.g. “/home/coolStuff/csProjects/”– a file’s name

• e.g. “App.java”– when it was last modified– whether or not it is a directory or just a file

• Operations include, among other things:– accessors and mutators for the path and name– operations to open and close files– operations to read and write to files (more on this

shortly…)

November 10, 2005Input and Output 18 of 26

Types of Files• You’ve probably been exposed to files of

different “types” i.e., they must be opened by different programs

• There are, however, two fundamental types of files

• Text files– contain characters you can type on the keyboard

• words• numbers• words in other alphabets• the source files (*.java) of your programs are text files

• Binary files– may include text, but also include some symbols that

cannot be represented as text– usually must be interpreted by another program, or

can actually be executed!• your compiled class files (*.class) are binary files• the program “javac” is an executable binary file• most pictures (*.jpg or *.gif) are binary files

• For the rest of this lecture, we will be concerning ourselves with text files

November 10, 2005Input and Output 19 of 26

Creating a File

In Java, there is a class which is used to represent a file. (Surprise! Surprise!)– The class is in the package java.io

• To create a file object we need only call the constructor of this class with the path to the file, or just the name of the file if it is in the current directory– e.g. new java.io.File(“testData.dat”);

• Note that this is not the same as actually creating a file on disk!– creating a new File object just connects our program

to a file.

November 10, 2005Input and Output 20 of 26

Like Drinking from a Fire Hose

• That’s all well and good, but how do we access the text in a file?

• Answer: with streams!

• The sequence of bytes flowing to or from an open file is referred to as a stream– this is true for both binary and text files– again, from the standpoint of an object oriented

programmer, streams are just objects with properties and capabilities

• There are various kinds of streams– InputStreams, OutputStreams, PrintStreams,

etc…– all are meant for different applications

November 10, 2005Input and Output 21 of 26

What can Streams Do?

• All streams just represent a collection bytes– these bytes are not directly accessible, however

• Input streams allow you to read one or more bytes from a stream–  int read(byte[] b, int offset, int len)– read len bytes starting from offset into the array b

• Output streams allow you to write one or more bytes to a stream– void write(byte[] b, int offset, int len)– write len bytes from b starting from offset into the

stream

• But these methods are a bit… clumsy– to write a piece of text to a file, we would have to create

a String, get an array of bytes which represents that String, and write that array to an open stream for that file

• If we’re dealing with text files, it would be nice to be able to work with files directly in terms of Strings…

November 10, 2005Input and Output 22 of 26

The Final Piece of the Puzzle

• Lucky for us, Java provides classes to make reading and writing to streams easy

• Readers and Writers exist to provide convenient ways to work with character streams– LineNumberReader/Writer– FileReader/Writer– BufferedReader/Writer– PipedReader/Writer– etc.

• All readers and writers extend from the abstract classes Reader and Writer– all must implement read or write, respectively– but most implement other helper methods or

convenience constructors

• Thanks, Java!

• We are finally ready… let’s see some code

November 10, 2005Input and Output 23 of 26

Let’s See an example…• Let’s do something simple. We want to read in every line of

a plain-text file and spit it back out to the console

public class FileToConsole {

public FileToConsole() { // Connect to the file called testData.dat // in the current directory File file = new File("testData.dat");

FileReader fileReader = null; try { // Must try-catch getting reader

// because here we are actually // opening the file fileReader = new FileReader(file); } catch(FileNotFoundException e) { // Could not find the file, so // display an error and exit gracefully System.out.println("Could not open file,

exiting."); System.exit(0); }

// Class continued on the next page

November 10, 2005Input and Output 24 of 26

Example continued…

// Use a LineNumberReader to get input one // line at a time LineNumberReader lineReader = new LineNumberReader(fileReader);

String line; try { // Repeat reading into line until // readLine() returns null while((line = lineReader.readLine())

!= null)

{ // Print out the line we just read System.out.println(line); } } catch(IOException e) { // Again, if we get an error, print a // message System.out.println("IOException while

reading file."); } finally { // Cleanup by closing our readers

fileReader.close(); lineReader.close(); } }} // End of class FileToConsole

November 10, 2005Input and Output 25 of 26

Writing to a file

• Now we want to write from console to a file:

public class ConsoleToFile {

public ConsoleToFile() {

// Connect to a file named outputData.dat // in the current directory File file = new File("outputData.dat");

PrintWriter fileWriter = null; try { // Must try-catch getting writer // because here we are actually opening

// the file fileWriter = new PrintWriter(file); } catch(FileNotFoundException e) { // Print a message and exit gracefully System.out.println("Could not open

file. Exiting."); System.exit(0); } // Continued on next slide

November 10, 2005Input and Output 26 of 26

Writing continued

// New reader for the stream System.in BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String line = ""; System.out.println("Enter data for file, one line at a time. q to quit."); try { // Read in until we hit a ‘q’ while(line.equals("q") == false) { // Read in a line from the console line = in.readLine(); // Write it out to a file fileWriter.println(line); } } catch(IOException e) { System.out.println("IOException while reading file."); } finally { fileWriter.close(); in.close(); } }} // End of class ConsoleToFile

November 10, 2005Input and Output 27 of 26