CS F213: Object Oriented Programming: Dipanjan Chakraborty Department of CS&IS
CS F213: Object Oriented Programming: Dipanjan Chakraborty Department of CS&IS
CS F213: Object Oriented Programming: Dipanjan Chakraborty Department of CS&IS
Dipanjan Chakraborty
Department of CS&IS
1
I/O in Java
●
Most real-world Java programs are not console-
based
– Rather, they are GUI based or web-based
●
Java’s support for console I/O is limited and
verbose
●
But, Java does have strong I/O capabilities for
network and files
2
Streams
●
Java I/O is based on the streams abstraction
●
A stream can produce or consume information
– A stream is linked to a physical device (keyboard, mouse,
monitor, network socket, etc.)
– The same I/O methods can be applied to different types of
devices
●
java.io package provides stream based I/O
●
java.nio package provides buffer-based I/O (later)
3
Streams
●
Java provides two types of streams:
– Byte streams
– Character streams
4
Byte Streams
●
Byte Streams provide a convenient way of handling input and output of
bytes
●
At the top are two abstract classes: InputStream and OutputStream
–
They have several concrete subclasses that handle the differences
among various devices, such as disk files, network connections,
memory buffers, etc.
–
Refer to Table 13-1 in the text book for a list of non-deprecated Byte
Stream classes in java.io
●
The abstract classes define several methods implemented by the
subclasses
–
Most important ones: read() and write()
5
Character Streams
●
Character Streams provide a convenient way of handling input
and output of characters
●
At the top are two abstract classes: Reader and Writer
–
These handle Unicode character streams
–
Refer to Table 13-2 in the text book for a list of non-
deprecated Character Stream classes in java.io
●
The abstract classes define several methods implemented by
the subclasses
–
Most important ones: read() and write()
6
Familiar Streams
●
The System class in java.lang contains three predefined streams:
in, out and err
– These are declared as public, static, final
●
System.out: standard output stream (default: console
●
System.in: standard input stream (default: keyboard)
●
System.err: standard error stream (default: console)
●
All three are objects of class PrintStream and are byte streams
7
Reading Console Input
●
Refer to exercises in the lab and in the
assignments
●
Recommended constructor:
– InputStreamReader(InputStream
inputStream, Charset charset)
8
Reading Console Input
9
Reading Characters
1 char c;
2 BufferedReader br = new BufferedReader(new
InputStreamReader(System.in, System.console().charset()));
3 System.out.println("Enter characters, 'q' to quit.");
4 do {
5 c = (char) br.read();
6 System.out.println(c);
7 } while(c != 'q');
10
Reading Strings
1 String str;
2 BufferedReader br = new BufferedReader(new
InputStreamReader(System.in, System.console().charset()));
3 System.out.println("Enter lines of text, 'stop' to quit.");
4 do {
5 str = br.readLine();
6 System.out.println(str);
7 } while(!str.equals("stop");
11
Writing Console Output
●
The print() and println() methods are defined
in the class PrintStream
– System.out is an object of type PrintStream
●
void write(int byteval)
1 int b;
2 b = 'A';
3 System.out.write(b);
4 System.out.write('\n');
12
Writing Console Output
●
PrintWriter stream
●
PrintWriter(OutputStream outputStream, boolean flushingOn)
●
There is nothing wrong with using System.out to write simple
text output. However, using a PrintWriter makes real-world
applications easier to internationalize.
13
Reading and Writing Files
●
FileInputStream and FileOutputStream create byte streams
linked to files
●
FileInputStream(String fileName) throws FileNotFoundException
●
FileOutputStream(String fileName) throws FileNotFoundException
●
When creating an InputStream, if the file does not exist, a FileNotFoundException is
thrown
●
When an output file is opened, any preexisting file by the same name is destroyed.
If the file cannot be opened or created, then a FileNotFoundException is thrown.
●
File streams are closed using the close() method (legacy code prior to JDK 7)
14
Reading from Files
●
FileInputStream and FileOutputStream create byte streams
linked to files
●
FileInputStream(String fileName) throws FileNotFoundException
●
FileOutputStream(String fileName) throws FileNotFoundException
●
When creating an InputStream, if the file does not exist, a FileNotFoundException is
thrown
●
When an output file is opened, any preexisting file by the same name is destroyed.
If the file cannot be opened or created, then a FileNotFoundException is thrown.
●
File streams are closed using the close() method (legacy code prior to JDK 7)
15
Reading bytes from Files
1 int i;
2 FileInputStream fin;
3 try {
4 fin = new FileInputStream(args[0]);
5 } catch(FileNotFoundException e) {...}
6
7 try {
8 do {
9 i = fin.read();
10 if(i != -1) System.out.print((char) i);
11 } while(i != -1);
12 } catch(IOException e) {...}
13
14 finally {
15 try {
16 fin.close();
17 } catch(IOException e) {...} 16
18 }
Writing bytes to Files
1 int i;
2 FileInputStream fin = null;
3 FileOutputStream fout = null;
4 try {
5 fin = new FileInputStream(args[0]);
6 fout = new FileOutputStream(args[1]);
7 do {
8 i = fin.read();
9 if(i != -1) fout.write(i);
10 } while(i != -1);
11 } catch(IOException e) {...}
12 finally {
13 try {
14 if(fin != null) fin.close();
15 } catch(IOException e2) {...}
16 try {
17 if(fout != null) fout.close();
18 } catch(IOException e2) {...} 17
19 }
Try with resources
●
Recall our discussion on Exceptions
●
Automatic Resource Management (ARM):
– prevents situations in which a file (or other resource) is inadvertently not released after it is no longer
needed
●
try (resource-specification) {
// use the resource
}
●
When the try block ends, the resource is automatically released. The resource declared in the try
statement is implicitly final
●
The try-with-resources statement can be used only with those resources that implement the
AutoCloseable interface defined by java.lang
– This interface defines the close( ) method
– AutoCloseable is inherited by the Closeable interface in java.io. Both interfaces are implemented by the
stream classes. Thus, try-with-resources can be used when working with streams, including file streams
18
Try with resources
1 int i;
2 If (args.length != 1) {
3 System.out.println("Usage: ShowFile filename");
4 return;
5 }
6 // try(var fin = new FileInputStream(args[0])) {
7 try(FileInputStream fin = new FileInputStream(args[0])) {
8 do {
9 i = fin.read();
10 if(i != -1) System.out.print((char) i);
11 } while(i != -1);
12 } catch(FileNotFoundException e) {
13 System.out.println("File Not Found.");
14 } catch(IOException e) {
15 System.out.println("An I/O Error Occurred");
16 }
19
Try with resources
1 try (FileInputStream fin = new FileInputStream(args[0]);
2 FileOutputStream fout = new FileOutputStream(args[1]))
3 {
4 ...
5 }
20
Serialization
●
Serialization is the process of writing the state of
an object to a byte stream
– Useful in saving the state of a program to a persistent
storage area such as a file or pass to a serial stream
like a network
– Later, one may restore these objects by using the
process of deserialization.
21
Serializable interface
●
Only an object that implements the Serializable
interface can be saved and restored by the
serialization facilities
– The interface contains no members
●
static and transient (discussed later) variables
are not saved by serialization
22
ObjectOutputStream
●
ObjectOutputStream class extends OutputStream
class and implements ObjectOutput interface
– ObjectOutputStream(OutputStream
outStream) throws IOException
23
ObjectInputStream
●
ObjectInputStream class extends InputStream
class and implements ObjectInput interface
– ObjectInputStream(InputStream
inStream) throws IOException
24
Serialization Example
1 class MyClass implements Serializable {
2 String s;
3 int i;
4 double d;
5 public MyClass(String s, int i, double d) {
6 this.s = s;
7 this.i = i;
8 this.d = d;
9 }
10 public String toString() {
11 return "s=" + s + "; i=" + i + "; d=" + d;
12 }
13 }
25
Serialization Example
1 try ( ObjectOutputStream objOStrm = new ObjectOutputStream(new
FileOutputStream("serial")) )
2 {
3 MyClass object1 = new MyClass("Hello", -7, 2.7e10);
4 System.out.println("object1: " + object1);
5 objOStrm.writeObject(object1);
6 }
7 catch(IOException e) {...}
8
9 try ( ObjectInputStream objIStrm = new ObjectInputStream(new
FileInputStream("serial")) )
10 {
11 MyClass object2 = (MyClass)objIStrm.readObject();
12 System.out.println("object2: " + object2);
13 }
14 catch(Exception e) {...} 26
transient modifier
●
When an instance variable is declared as
transient, its value need not persist when an
object is stored in a persistent storage area
●
class T {
transient int a; // will not persist
int b; // will persist
}
27