Professional Documents
Culture Documents
Programming
Lecture # 17: IO
Muhammad Imran
1
Outline
•Streams
•Opening and Using Streams
•Reading Lines
•Using Scanner Class
•LineReader and LineWriter (Custom Class)
•PrintWriter Class
•Using JFileChooser
•Serialization
2
Streams
•All modern I/O is stream-based
•A stream is a connection to a source of data or to a
destination for data (sometimes both)
•An input stream may be associated with the keyboard
•An input stream or an output stream may be associated
with a file
•Different streams have different characteristics:
A file has a definite length, and therefore an end
Keyboard input has no specific end
3
Streams
•An abstraction of the continuous one-way data pipe
•Transfers a sequence of bytes to or from
Disk files
Network connections
Memory
Threads
•Streams are either byte-oriented or character-oriented
An IOException may occur during any IO operation
4
• In Java, three streams are created automatically and attached with
the console.
System.out: standard output stream
System.in: standard input stream
System.err: standard error stream
System.out.println("simple message");
System.err.println("error message");
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
5
How to do I/O
import java.io.*;
6
open
use
Why Java I/O is hard close
7
open
use
Opening a stream close
• Once the connection is made, you forget about the external place
and just use the stream
8
open
Example of opening a stream use
close
9
open
use
Using a stream close
• Some streams can be used only for input, others only for output,
still others for both
• But it’s not usually that simple--you need to manipulate the data
in some way as it comes in or goes out
10
open
use
Example of using a stream close
• int charAsInt;
charAsInt = fileReader.read( );
11
open
use
Manipulating the input data close
• A BufferedReader will convert integers to characters; it can also read whole lines
12
open
use
Reading lines close
• String s;
s = bufferedReader.readLine( );
13
open
use
Closing close
• Java will normally close your streams for you when your program
ends, but it isn’t good style to depend on this
14
Review: Scanner
• We've seen Scanner before
• The constructor takes an object of type
java.io.InputStream – stores information about the
connection between an input device and the computer or
program
Example: System.in
• Recall – only associate one instance of Scanner with
System.in in your program
Otherwise, get bugs
15
Reading Files
•The same applies for both console input and file input
16
Reading Files
• To read from a disk file, construct a FileReader
17
Reading Files
• You can use File instead of FileReader
Has an exists() method we can call to avoid
FileNotFoundException
18
Reading Files
• Once we have a Scanner, we can use methods we already know:
next, nextLine, nextInt, etc.
19
File Class
• java.io.File
associated with an actual file on hard drive
used to check file's status
• Constructors
File(<full path>)
File(<path>, <filename>)
• Methods
exists()
canRead(), canWrite()
isFile(), isDirectory()
20
FileReader Class
•java.io.FileReader
Associated with File object
Translates data bytes from File object into a stream of
characters (much like InputStream vs.
InputStreamReader)
• Constructors
FileReader( <File object> );
• Methods
read(), readLine()
close()
21
Simple Java I/O
Part II
LineReader and LineWriter
22
Text files
• Text (.txt) files are the simplest kind of files
Text files can be used by many different programs
• Only programs that “know the secret code” can make sense of
formatted text files
23
My LineReader class
class LineReader {
BufferedReader bufferedReader;
24
Basics of the LineReader constructor
• Create a FileReader for the named file:
FileReader fileReader =
new FileReader(fileName);
25
The full LineReader constructor
LineReader(String fileName) {
FileReader fileReader = null;
try { fileReader = new FileReader(fileName); }
catch (FileNotFoundException e) {
System.err.println
("LineReader can’t find input file: " + fileName);
e.printStackTrace( );
}
bufferedReader = new BufferedReader(fileReader);
}
26
readLine
String readLine( ) {
try {
return bufferedReader.readLine( );
}
catch(IOException e) {
e.printStackTrace( );
}
return null;
}
27
close
void close() {
try {
bufferedReader.close( );
}
catch(IOException e) { }
}
28
How did I figure that out?
• I wanted to read lines from a file
• I thought there might be a suitable readSomething method, so I went to the
API Index
Note: Capital letters are all alphabetized before lowercase in the Index
• I found a readLine method in several classes; the most promising was the
BufferedReader class
• The constructor for BufferedReader takes a Reader as an argument
• Reader is an abstract class, but it has several implementations, including
InputStreamReader
• FileReader is a subclass of InputStreamReader
• There is a constructor for FileReader that takes as its argument a (String)
file name
29
The LineWriter class
class LineWriter {
PrintWriter printWriter;
30
The constructor for LineWriter
LineWriter(String fileName) {
try {
printWriter =
new PrintWriter(
new FileOutputStream(fileName),
true);
}
catch(Exception e) {
System.err.println("LineWriter can’t " +
"use output file: " + fileName);
}
}
31
Flushing the buffer
• When you put information into a buffered output stream, it goes
into a buffer
• If your program crashes, you may not know how far it got before it
crashed
32
PrintWriter
• Buffers are automatically flushed when the program ends
normally
• Usually it is your responsibility to flush buffers if the program
does not end normally
• We can use a PrintWriter object to write to a file
• How do we use a PrintWriter object?
Have we already seen one?
33
Writing to a File using PrintWriter
• The out field of the System class is a PrintWriter object
associated with the console
We will associate our PrintWriter with a file now
34
writeLine (updated using PrintWriter)
35
close
void close( ) {
printWriter.flush( );
try {
printWriter.close( );
}
catch(Exception e) { }
}
36
Java Input Review
CONSOLE:
FILE:
37
Java Output Review
• CONSOLE:
• FILE:
PrintWriter fout =
new PrintWriter(new File("output.txt");
fout.print("To a file");
38
Simple Java I/O
Part III
JFileChooser
39
About JFileChoosers
• The JFileChooser class displays a window from which the user
can select a file
40
Typical JFileChooser window
41
JFileChooser constructors
• JFileChooser()
Creates a JFileChooser starting from the user’s directory
• JFileChooser(File currentDirectory)
Constructs a JFileChooser using the given File as the path
• JFileChooser(String currentDirectoryPath)
Constructs a JFileChooser using the given path
42
Useful JFileChooser methods I
• int showOpenDialog(Component enclosingJFrame);
Asks for a file to read; returns a flag (see below)
43
Useful JFileChooser methods II
•File getSelectedFile()
showOpenDialog and showSaveDialog return a flag telling
what happened, but don’t return the selected file
After we return from one of these methods, we have to ask the
JFileChooser what file was selected
If we are saving a file, the File may not actually exist yet—that’s
OK, we still have a File object we can use
44
Using a File
• Assuming that we have successfully selected a File:
46
Serialization
• You can also read and write objects to files
47
Conditions for serializability
•If an object is to be serialized:
The class must be declared as public
The class must implement Serializable
The class must have a no-argument constructor
All fields of the class must be serializable: either primitive
types or serializable objects
48
Implementing Serializable
• To “implement” an interface means to define all the methods
declared by that interface, but...
49
Writing objects to a file
ObjectOutputStream objectOut =
new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(fileName)));
objectOut.writeObject(serializableObject);
objectOut.close( );
50
Reading objects from a file
ObjectInputStream objectIn =
new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
myObject = (itsType)objectIn.readObject( );
objectIn.close( );
51
What have I left out?
• Encrypted files, compressed files, files sent over internet connections, ...
52
try with resources
• try-with-resources, is an exception handling mechanism that can
automatically close resources once done!!
• You must open and use the resource within a Java try-with-
resources block.
53
Example:
public static void main (String[] args) throws IOException {
while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}
54