CSC111H_JavaIO-web

Download Report

Transcript CSC111H_JavaIO-web

I/O in Java
Dennis Burford
[email protected]
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.
Streams
• Java uses the concept of Streams
for I/O
• Data flows from a Writer
to a Reader
Writer
Stream
Reader
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
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();
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.
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.
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)
Using System.in
'f','i','r','s','t','\n','1','2','3','\n','4','2',' ','5','8','\n', ...
InputStream.read()
System.in
'f'
• read() method reads one character at a time.
• Returns an int
• Returns –1 for EOF (End of File = Ctrl-Z)
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);
}
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();
}
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);
Reading Strings
'f', 'i','r' ,'s','t' ,'1','2 ','3',' \n','4', '2',' ' ,'5','8 ','\n', ...
InputStream.read()
System.in stream
InputStreamReader.read()
an InputStreamReader object
'f'
Reading Strings
• Next, wrap InputStreamReader object in
BufferedReader object:
InputStreamReader ISReader
= new InputStreamReader(System.in);
BufferedReader BufReader
= new BufferedReader(ISReader);
Reading Strings
• Can combine these into a single statement:
BufferedReader BufReader
= new BufferedReader(new InputStreamReader(System.in));
Reading Strings
• Can combine these into a single statement:
BufferedReader BufReader
= new BufferedReader(new InputStreamReader(System.in));
InputStream
InputStreamReader
BufferedReader
Reading Strings
• Methods in BufferedReader
– read()
– readLine()
• Read a string by using readLine() method:
String str = BufReader.readLine();
Reading Strings
'f','i','r','s','t','\n','1','2','3','\n','4','2',' ','5','8','\n', ...
InputStream.read()
System.in stream
InputStreamReader.read()
an InputStreamReader object
BufferedReader.readLine()
a BufferedReader object
"first"
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));
...
}
}
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));
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);
}
}
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: Linda
Enter your last name: Jones
Your name is Linda Jones
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.
'1','2','3','\n','4','2',' ','5','8','\n', ...
InputStream.read()
System.in stream
InputStreamReader.read()
an InputStreamReader object
BufferedReader.readLine()
a BufferedReader object
"123"
NumberFormatter.parse()
Number(123)
Number.intValue()
123
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();
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
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();
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
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
'4','2',' ','5','8','\n', ...
InputStream.read()
System.in stream
InputStreamReader.read()
an InputStreamReader object
BufferedReader.readLine()
a BufferedReader object
"42 58"
StringTokenizer()
StringTokenizer.nextToken()
a StringTokenizer object
"42","58"
Input Streams: Multiple Values
StringTokenizer tokenizer = new StringTokenizer("42 58");
String token;
token = tokenizer.nextToken();
System.out.println(token);
// Displays 42
token = tokenizer.nextToken();
System.out.println(token);
// Displays 58
• BETTER…
StringTokenizer tokenizer = new StringTokenizer("42 58");
while (tokenizer.hasMoreTokens())
{
System.out.println(tokenizer.nextToken());
}
FILES
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).
Types of Files
Summer.txt
Rough winds do shake the darling buds of May\n
And Summer’s lease hath all too short a date\n
Sometime too hot the eye of heaven shines,\n
And oft is his gold complexion dimmed,\n
And every fair from fair sometime declines...
Numbers.dat
Œpôw10Žé¿l%®ú€9câÜ(3xLenfˆx¹ª(
Ͻ»¼øß:° µ
œŒÝçMÙ¾à:ˆqfõÑ>|èœ=L¶
...
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
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
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
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
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
}
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
}
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
}
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
}
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
}
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
}
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
BufferedReader
FileReader
File
// Initialize the file variable
File inFile = new File(”Summer.txt");
// Make sure the file can be read from
if (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
}
// Initialize the file variable
File inFile = new File(”Summer.txt");
// Make sure the file can be read from
if (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
}
// Initialize the file variable
File inFile = new File(”Summer.txt");
// Make sure the file can be read from
if (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
}
// Initialize the file variable
File inFile = new File(”Summer.txt");
// Make sure the file can be read from
if (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
}
// Initialize the file variable
File inFile = new File(”Summer.txt");
// Make sure the file can be read from
if (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
}
// Initialize the file variable
File inFile = new File(”Summer.txt");
// Make sure the file can be read from
if (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”
Text Files: Reading from a File
• Can do same things we did with System.in
– Read numbers (NumberFormat)
– Read multiple “tokens” (StringTokenizer)
Text Files: Writing to a File
• Before writing, make sure either...
– File doesn't exist
!outFile.exists()
– Or file exists, and is writeable
outFile.exists() && outFile.canWrite()
• Combine conditions
!outFile.exists() || outFile.canWrite()
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
PrintWriter
BufferedWriter
FileWriter
File
// Initialize the file variable
File outFile = new File(”New.txt");
// Make sure that the file either doesn't exist or
// we can write to it
if (!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
}
// Initialize the file variable
File outFile = new File(”New.txt");
// Make sure that the file either doesn't exist or
// we can write to it
if (!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
}
// Initialize the file variable
File outFile = new File(”New.txt");
// Make sure that the file either doesn't exist or
// we can write to it
if (!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
}
// Initialize the file variable
File outFile = new File(”New.txt");
// Make sure that the file either doesn't exist or
// we can write to it
if (!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
}
// Initialize the file variable
File outFile = new File(”New.txt");
// Make sure that the file either doesn't exist or
// we can write to it
if (!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
}
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
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");
Text Files: Writing to a File
• Once finished writing to the file, close it
pWriter.close();
Java I/O Summary
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 )))