66
I/O in Java Dennis Burford [email protected]

I/O in Java Dennis Burford [email protected]

Embed Size (px)

Citation preview

Page 1: I/O in Java Dennis Burford dburford@cs.uct.ac.za

I/O in Java

Dennis Burford

[email protected]

Page 2: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Input and Output

• Obtaining input:– Using BasicIo methods.

– Through a GUI

• Producing output:– Using System.out methods (System.out.println())

– Through a GUI

• Other input/output: files, sockets etc.

Page 3: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Streams• Java uses the concept of Streams

for I/O

• Data flows from a Writer to a Reader

ReaderWriter Stream

Page 4: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Why Streams?• Stream generalizes input & output

– Keyboard electronics different from disk– Input stream makes keyboard and files seem the

same to a Reader

Input Stream Reader

Page 5: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Simplified Keyboard Input…

• “Java: First Contact” uses BasicIo class– String name = BasicIo.readString();– int age = BasicIo.readInteger();

• Slack textbook uses Keyboard class– String name = Keyboard.readString();– int age = Keyboard.readInt();

Page 6: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Simplified Keyboard Input…

• Both BasicIo and Keyboard are wrapper classes used to hide detail.

• In reality, both classes use System.in and other low-level Java classes to operate.

Page 7: I/O in Java Dennis Burford dburford@cs.uct.ac.za

System class

• System class is inside java.lang package• Contains 2 variables:

public static final InputStream in;public static final PrintStream out;

• System.in is usually connected to the user’s keyboard.

• System.out is usually connected to the user’s screen.

Page 8: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Using System.in

• System.in is an InputStream

• Can use System.in many ways

– Directly (low-level access)– Through layers of abstraction (high-level

access)

Page 9: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Using System.in

• read() method reads one character at a time.• Returns an int• Returns –1 for EOF (End of File = Ctrl-Z)

System.in

'f'

InputStream.read()

'f','i','r','s','t','\n','1','2','3','\n','4','2',' ','5','8','\n', ...

Page 10: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Using System.in

public static void main(String[] args) throws java.io.IOException { char character;

// Prompt for a character and read it System.out.print("Enter a character: "); System.out.flush(); character = (char) System.in.read(); // Display the character typed System.out.println(); System.out.println("You typed " + character); }

Page 11: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Using System.in

int intChar = System.in.read();

while (intChar != -1){ // Convert to character char character = (char) intChar;

System.out.println("Next character is " + character);

// Get next one intChar = System.in.read();}

Page 12: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Reading Strings

• No String-reading methods in System.in

• To read strings from keyboard, first wrap System.in inside InputStreamReader object:

InputStreamReader ISReader = new InputStreamReader(System.in);

Page 13: I/O in Java Dennis Burford dburford@cs.uct.ac.za

InputStreamReader.read()

an InputStreamReader object

InputStream.read()

'f','i','r','s','t','1','2','3','\n','4','2',' ','5','8','\n', ...

System.in stream

'f'

Reading Strings

Page 14: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Reading Strings

• Next, wrap InputStreamReader object in BufferedReader object:

InputStreamReader ISReader

= new InputStreamReader(System.in);

BufferedReader BufReader

= new BufferedReader(ISReader);

Page 15: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Reading Strings

• Can combine these into a single statement:

BufferedReader BufReader

= new BufferedReader(new InputStreamReader(System.in));

Page 16: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Reading Strings

• Can combine these into a single statement:

BufferedReader BufReader

= new BufferedReader(new InputStreamReader(System.in));

InputStream

InputStreamReader

BufferedReader

Page 17: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Reading Strings

• Methods in BufferedReader– read()– readLine()

• Read a string by using readLine() method:

String str = BufReader.readLine();

Page 18: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Reading Strings

InputStreamReader.read()

an InputStreamReader object

InputStream.read()

'f','i','r','s','t','\n','1','2','3','\n','4','2',' ','5','8','\n', ...

System.in stream

"first"

BufferedReader.readLine()

a BufferedReader object

Page 19: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Reading Strings• InputStreamReader, BufferedReader in java.io.*

• Skeleton for reading:

import java.io.*;

class ClassName{ public static void main(String[] args)

throws java.io.IOException { // Create a buffered input stream and attach it to standard // input BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); ... }}

Page 20: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Example: Reading User’s Name// Reads a user's first name and last name. // Demonstrates use of InputStreamReader, // BufferedReader and the readLine() method.

import java.io.*;

class ReadInputAsString{ public static void main(String[] args) throws java.io.IOException { String firstName, lastName; // Create an input stream and attach it to the standard // input stream BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in));

Page 21: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Example: Reading User’s Name // Read a line from the user as a String

System.out.print("Enter your first name: "); System.out.flush(); firstName = BufReader.readLine();

// Read a line from the user as a String System.out.print("Enter your last name: ");

System.out.flush(); lastName = BufReader.readLine();

// Display the strings System.out.println(); System.out.println("Your name is" + firstName + lastName); }}

Page 22: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Example: Reading User’s Name // Read a line from the user as a String

System.out.print("Enter your first name: "); System.out.flush(); firstName = BufReader.readLine();

// Read a line from the user as a String System.out.print("Enter your last name: ");

System.out.flush(); lastName = BufReader.readLine();

// Display the strings System.out.println(); System.out.println("Your name is" + firstName + lastName); }}

Enter your first name: LindaEnter your last name: Jones

Your name is Linda Jones

Page 23: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Formatting Numbers

• Alternative to Integer.parseInt() etc.

• NumberFormat– Object factory: use getInstance()– parse() takes a string and returns a Number– parse() throws java.text.ParseException

• General Number class– Return value using intValue(), doubleValue() etc.

Page 24: I/O in Java Dennis Burford dburford@cs.uct.ac.za

InputStreamReader.read()

an InputStreamReader object

InputStream.read()

'1','2','3','\n','4','2',' ','5','8','\n', ...

System.in stream

"123"

BufferedReader.readLine()

a BufferedReader object

NumberFormatter.parse()

Number(123)

Number.intValue()

123

Page 25: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Formatting Numbers from Kbd

NumberFormat formatter = NumberFormat.getInstance();

BufferedReader BufReader

= new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter an integer: ");

System.out.flush();

String response = BufReader.readLine();

Number numberObj = formatter.parse(response);

int numberInt = numberObj.intValue();

Page 26: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Formatting Numbers from Kbd

NumberFormat formatter = NumberFormat.getInstance();

BufferedReader BufReader

= new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter an integer: ");

System.out.flush();

String response = BufReader.readLine();

Number numberObj = formatter.parse(response);

int numberInt = numberObj.intValue();

Combine

Page 27: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Formatting Numbers from Kbd

NumberFormat formatter = NumberFormat.getInstance();

BufferedReader BufReader

= new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter an integer: ");

System.out.flush();

int numberInt

= formatter.parse( BufReader.readLine() ).intValue();

Page 28: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Formatting Numbers from Kbd

NumberFormat formatter = NumberFormat.getInstance();

BufferedReader BufReader

= new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter an integer: ");

System.out.flush();

int numberInt

= formatter.parse( BufReader.readLine() ).intValue();

Don’t forget to throw or catch java.text.ParseException

Don’t forget to throw or catch java.text.ParseException

Page 29: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Input Streams: Multiple Values

• To read several values on one line– Use StringTokenizer object– Breaks one string into component parts– Must still convert numbers (if necessary)

• StringTokenizer– Constructor takes string– nextToken() method– hasMoreTokens() method

Page 30: I/O in Java Dennis Burford dburford@cs.uct.ac.za

"42","58"

StringTokenizer()

StringTokenizer.nextToken()

a StringTokenizer object

InputStreamReader.read()

an InputStreamReader object

InputStream.read()

'4','2',' ','5','8','\n', ...

System.in stream

"42 58"

BufferedReader.readLine()

a BufferedReader object

Page 31: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Input Streams: Multiple Values

StringTokenizer tokenizer = new StringTokenizer("42 58");

String token;token = tokenizer.nextToken();System.out.println(token); // Displays 42token = tokenizer.nextToken();System.out.println(token); // Displays 58

• BETTER…

StringTokenizer tokenizer = new StringTokenizer("42 58");while (tokenizer.hasMoreTokens()){ System.out.println(tokenizer.nextToken());}

Page 32: I/O in Java Dennis Burford dburford@cs.uct.ac.za

FILES

Page 33: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Overview of Files

• How they are accessed:– sequential: data items must be accessed in the order in

which they are stored (ie. start at the beginning and pass through all the items)

– direct (or random): items are accessed by specifying their location

• How information is represented:– text files: data is stored in character form.– binary files: data is stored in internal binary form (faster

and more compact than text files).

Page 34: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Types of Files

Summer.txt

Rough winds do shake the darling buds of May\nAnd Summer’s lease hath all too short a date\nSometime too hot the eye of heaven shines,\nAnd oft is his gold complexion dimmed,\nAnd every fair from fair sometime declines...

Numbers.dat

Œpôw10Žé¿l%®ú€9câÜ(3xLenfˆx¹ª(Ͻ»¼øß:°µœŒÝçMÙ¾à:ˆqfõ�Ñ>|èœ=L¶...

Page 35: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files

• Text file– human-readable with simple tools (Notepad, Ready, ...)– Each line terminated by end-of-line marker (‘\n’)– Example: .java files

• Easy to read and write text files– Advantage of "streams" approach to I/O– Use same classes and methods as System.in and System.out

Page 36: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: The File Class

• Need File object for each file program uses– File inFile = new File(”Summer.txt");

• Purpose– Contains information about the file

– A “go-between” for the file

– Not the same as the file itself

Page 37: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: The File Class

• Methods in the File class– exists(): Tells if the file is there– canRead(): Tells if program can read the file– canWrite(): Tells if program can write to the file– delete(): Deletes the file– isDirectory(): Tells if file is really a directory name– isFile(): Tells if the file is a file (not a directory)– length(): Tells the length of the file, in bytes

Page 38: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: The File Class

• Methods in the File class– exists(): Tells if the file is there– canRead(): Tells if program can read the file– canWrite(): Tells if program can write to the file– delete(): Deletes the file– isDirectory(): Tells if file is really a directory name– isFile(): Tells if the file is a file (not a directory)– length(): Tells the length of the file, in bytes

Page 39: I/O in Java Dennis Burford dburford@cs.uct.ac.za

import java.io.*;

class TellIfExists{

public static void main(String[] args) throws java.io.IOException {

File myFile = new File(“Summer.txt”);

if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); }

} // end main

}

Page 40: I/O in Java Dennis Burford dburford@cs.uct.ac.za

import java.io.*;

class TellIfExists{

public static void main(String[] args) throws java.io.IOException {

File myFile = new File(“Summer.txt”);

if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); }

} // end main

}

Page 41: I/O in Java Dennis Burford dburford@cs.uct.ac.za

import java.io.*;

class TellIfExists{

public static void main(String[] args) throws java.io.IOException {

File myFile = new File(“Summer.txt”);

if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); }

} // end main

}

Page 42: I/O in Java Dennis Burford dburford@cs.uct.ac.za

import java.io.*;

class TellIfExists{

public static void main(String[] args) throws java.io.IOException {

File myFile = new File(“Summer.txt”);

if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); }

} // end main

}

Page 43: I/O in Java Dennis Burford dburford@cs.uct.ac.za

import java.io.*;

class TellIfExists{

public static void main(String[] args) throws java.io.IOException {

File myFile = new File(“Summer.txt”);

if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); }

} // end main

}

Page 44: I/O in Java Dennis Burford dburford@cs.uct.ac.za

import java.io.*;

class TellIfExists{

public static void main(String[] args) throws java.io.IOException {

File myFile = new File(“Summer.txt”);

if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); }

} // end main

}

Page 45: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: Reading from a File

• Before reading, make sure– File exists and is readable

inFile.exists() && inFile.canRead()

• Attach file to a stream– FileReader object: knows how to read stream from a file– Wrap FileReader object in BufferedReader object

• BufferedReader works on files just like System.in– read(): read a single character, or -1 if EOF– readLine(): read a line, or null if EOF

Page 46: I/O in Java Dennis Burford dburford@cs.uct.ac.za

File

FileReader

BufferedReader

Page 47: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile inFile = new File(”Summer.txt");

// Make sure the file can be read fromif (inFile.exists() && inFile.canRead()){ // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile));

// Read from file stream same way as reading // from the keyboard

String line = BufReader.readLine();}else{ // Error: Can't read from file}

Page 48: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile inFile = new File(”Summer.txt");

// Make sure the file can be read fromif (inFile.exists() && inFile.canRead()){ // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile));

// Read from file stream same way as reading // from the keyboard

String line = BufReader.readLine();}else{ // Error: Can't read from file}

Page 49: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile inFile = new File(”Summer.txt");

// Make sure the file can be read fromif (inFile.exists() && inFile.canRead()){ // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile));

// Read from file stream same way as reading // from the keyboard

String line = BufReader.readLine();}else{ // Error: Can't read from file}

Page 50: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile inFile = new File(”Summer.txt");

// Make sure the file can be read fromif (inFile.exists() && inFile.canRead()){ // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile));

// Read from file stream same way as reading // from the keyboard

String line = BufReader.readLine();}else{ // Error: Can't read from file}

Page 51: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile inFile = new File(”Summer.txt");

// Make sure the file can be read fromif (inFile.exists() && inFile.canRead()){ // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile));

// Read from file stream same way as reading // from the keyboard

String line = BufReader.readLine();}else{ // Error: Can't read from file}

Page 52: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile inFile = new File(”Summer.txt");

// Make sure the file can be read fromif (inFile.exists() && inFile.canRead()){ // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile));

// Read from file stream same way as reading // from the keyboard

String line = BufReader.readLine();}else{ // Error: Can't read from file}

line = “Rough winds do shake the darling buds of May”

Page 53: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: Reading from a File

• Can do same things we did with System.in

– Read numbers (NumberFormat)

– Read multiple “tokens” (StringTokenizer)

Page 54: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: Writing to a File

• Before writing, make sure either...– File doesn't exist

!outFile.exists()

– Or file exists, and is writeableoutFile.exists() && outFile.canWrite()

• Combine conditions!outFile.exists() || outFile.canWrite()

Page 55: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: Writing to a File

• Attach file to a stream

– FileWriter object: knows how to write stream to a file

– Wrap FileWriter object in BufferedWriter object

– Wrap BufferedWriter object in PrintWriter object

Page 56: I/O in Java Dennis Burford dburford@cs.uct.ac.za

File

FileWriter

BufferedWriter

PrintWriter

Page 57: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile outFile = new File(”New.txt");

// Make sure that the file either doesn't exist or// we can write to itif (!outFile.exists() || outFile.canWrite()){ // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile)));

// Write to the file pWriter.println( “This is the first line!” );

}else{ // Error: Can't write to the file}

Page 58: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile outFile = new File(”New.txt");

// Make sure that the file either doesn't exist or// we can write to itif (!outFile.exists() || outFile.canWrite()){ // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile)));

// Write to the file pWriter.println( “This is the first line!” );

}else{ // Error: Can't write to the file}

Page 59: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile outFile = new File(”New.txt");

// Make sure that the file either doesn't exist or// we can write to itif (!outFile.exists() || outFile.canWrite()){ // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile)));

// Write to the file pWriter.println( “This is the first line!” );

}else{ // Error: Can't write to the file}

Page 60: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile outFile = new File(”New.txt");

// Make sure that the file either doesn't exist or// we can write to itif (!outFile.exists() || outFile.canWrite()){ // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile)));

// Write to the file pWriter.println( “This is the first line!” );

}else{ // Error: Can't write to the file}

Page 61: I/O in Java Dennis Burford dburford@cs.uct.ac.za

// Initialize the file variableFile outFile = new File(”New.txt");

// Make sure that the file either doesn't exist or// we can write to itif (!outFile.exists() || outFile.canWrite()){ // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile)));

// Write to the file pWriter.println( “This is the first line!” );

}else{ // Error: Can't write to the file}

Page 62: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: Writing to a File

• System.out and pWriter both output streams

– System.out is PrintStream object– pWriter is PrintWriter object

– PrintStream and PrintWriter are almost identical (PrintWriter is newer)

– print(), println(), flush() work the same

Page 63: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: Writing to a File

• System.out and pWriter both output streams

– System.out is PrintStream object– pWriter is PrintWriter object

– PrintStream and PrintWriter are almost identical (PrintWriter is newer)

– print(), println(), flush() work the same

pWriter.print("This goes ");pWriter.println("to the file");

Page 64: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Text Files: Writing to a File

• Once finished writing to the file, close it

pWriter.close();

Page 65: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Java I/O Summary

Page 66: I/O in Java Dennis Burford dburford@cs.uct.ac.za

Java I/O Summary

• Reading from Keyboard– BufferedReader( InputStreamReader( System.in ))

• Writing to Screen– System.out

• Reading from File– BufferedReader( FileReader( File ))

• Writing to File– PrintWriter( BufferedWriter( FileWriter( File )))