Nothing Special   »   [go: up one dir, main page]

Java As An Object-Oriented Programming Language

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 64

Part 1:

Java as an Object-oriented
Programming Language

Java IO Stream
Files

2
Storage

Modern computers have many different kinds of storage


components:
- memory (aka RAM or DRAM)
- disks (aka “hard disks” or “hard drives”)
- caches
- external media (USB sticks, DVD, CD-RW, etc.)

Why so many?
Because they behave differently!

3
Memory vs. Disk

Typical Properties
Memory Disk
Capacity: 1-4 Gb >100 Gb
When power goes off: Data is lost Data is safe
When program ends: Data is lost Data is safe
Sequential access
1.2 GB / second 50 MB / second
speed:
Random access ??
1.2 GB / second
Tradeoff:
speed: ~ 66.7 seeks / second
Disks have greater capacity (more GB) and offer permanent storage;
Memory is much faster.

4
Files and Directories

 Your operating system (Windows, Mac, Linux, etc.)


divides your disk hierarchically
 This creates a tree structure
 Each element in the tree is a folder or directory
 Inside directories are files

tmp Hello.java

super3
C: Documents
and Settings All Users

Adobe
Program Files

WinShell
Files and Variables

 Recall variables:
 They have types, names, and a location in memory
 You can put data inside them, and use the data later

 Files are similar abstractions, but for the disk:


 They have names and a location on the disk
 You can put (lots of) data inside them
 You can later retrieve that data and use it
Two main file operations

 Read
 Move data from a file on the disk into a variable (or
variables) in memory
 Write
 Move data from a variable (or variables) in memory to a file
on the disk

 Two tricky details to these operations –


 Data types
 Checked Exceptions
File class

 The File class is a template for objects (in


memory) that represent actual files (on disk):
File myFile = new File(“C:\myfile.txt”);

 The File class is in the java.io package. To use


it, include the import declaration:

import java.io.*;

 io (or I/O) stands for input/output.

8
Reading data from text files

 Creating a Scanner for a file, general syntax:


Scanner <name> = new Scanner(new File("<file name>"));

 Example:
Scanner input = new Scanner(new File("numbers.txt"));

 Instead of getting data from the keyboard via


System.in, this Scanner object gets data from the file
numbers.txt in the current folder (directory).

9
Compiler error with files

 The following program does not compile:


1 import java.io.*; // for File
2 import java.util.*; // for Scanner
3
4 public class ReadFile {
5 public static void main(String[] args) {
6 Scanner input = new Scanner(new File("data.txt"));
7 // do something
8 }
9 }

 The compiler reports:


ReadFile.java:6: unreported exception
java.io.FileNotFoundException; must be caught or
declared to be thrown

10
Exceptions

 exception: An object representing a program error.


 Programs with invalid logic will cause ("throw")
exceptions.

 Examples:
 Trying to read a file that does not exist.
 Dividing by 0.
 Using charAt(10) on a string of length 5.

11
Checked exceptions

 checked exception: An exception that must be


explicitly handled (otherwise the program will not
compile).
 We must either:
• handle ("catch") the exception, or
• explicitly state that we choose not to handle the
exception (and accept that the program will crash if
the exception occurs)

12
throws clause: How to waive your
rights
 throws clause: Tells the compiler that a method
may throw an exception.
 Like a waiver of liability:
"I hereby agree that this method might throw an exception,
and I accept the consequences (crashing) if this happens."

 throws clause, general syntax:


public static <type> <name>(<params>) throws <type> {

 Example:
public static void main(String[] args)
throws FileNotFoundException {
13
Patched code

import java.io.*; // for File, FileNotFoundException


import java.util.*; // for Scanner

public class ReadFile {


public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("data.txt"));
// do something
}
}

14
Recap: Tokens

 The Scanner breaks apart the input into tokens. It will interpret
the tokens in different ways depending on if you call next(),
nextInt(), or nextDouble().

 Assuming the following input file:


23 3.14
"John Smith"

The tokens in the input can be interpreted as the given types:

Token Type(s)
1. 23 int, double, String
2. 3.14 double, String
3. "John String
4. Smith" String
15
The input cursor

 Consider a file that contains this text:


308.2
14.9 7.4 2.8

3.9 4.7 -15.4


2.8

 A Scanner views all input as a stream of


characters, which it processes with its input cursor:
308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7 -15.4\n2.8\n
^

16
Consuming tokens

 Each call to next, nextInt, nextDouble, etc.


advances the cursor to the end of the current token,
skipping over any whitespace. Each call consumes
the input.

 input.nextDouble();
308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7 -15.4\n2.8\n
^

 input.nextDouble();
308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7 -15.4\n2.8\n
^
17
Exercise: Version 1
 Consider an input file named input.txt:
308.2
14.9 7.4 2.8

3.9 4.7 -15.4


2.8

 Write a program that reads the first 5 values from this file and prints
them along with their sum.

Output:
number = 308.2
number = 14.9
number = 7.4
number = 2.8
number = 3.9
Sum = 337.19999999999993
18
Solution: Version 1
// Displays the first 5 numbers in the given file,
// and displays their sum at the end.

import java.io.*; // for File, FileNotFoundException


import java.util.*; // for Scanner

public class Echo {


public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("numbers.dat"));
double sum = 0.0;
for (int i = 1; i <= 5; i++) {
double next = input.nextDouble();
System.out.println("number = " + next);
sum += next;
}
System.out.println("Sum = " + sum);
}
}

19
Reading a whole file

 The preceding program is assumes you know how


many values you want to read.

 How could we read in ALL of the numbers in the file,


without knowing beforehand how many the file
contains?

20
Look before you read

 The Scanner has useful methods for testing to see


what the next input token will be.

Method Name Description


hasNext() whether any more tokens remain
hasNextDouble() whether the next token can be
interpreted as type double
hasNextInt() whether the next token can be
interpreted as type int
hasNextLine() whether any more lines remain
21
Exercise: Version 2

 Rewrite the previous program so that it reads the


entire file.

Output:
number = 308.2
number = 14.9
number = 7.4
number = 2.8
number = 3.9
number = 4.7
number = -15.4
number = 2.8
Sum = 329.29999999999995

22
Solution: Version 2
// Displays each number in the given file,
// and displays their sum at the end.

import java.io.*; // for File, FileNotFoundException


import java.util.*; // for Scanner

public class Echo2 {


public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("numbers.dat"));
double sum = 0.0;
while (input.hasNextDouble()) {
double next = input.nextDouble();
System.out.println("number = " + next);
sum += next;
}
System.out.println("Sum = " + sum);
}
}

23
Exercise: Version 3

 Modify the preceding program again so that it will


handle files that contain non-numeric tokens.
 The program should skip any such tokens.

 For example, the program should produce the same


output as before when given this input file:

308.2 hello
14.9 7.4 bad stuff 2.8

3.9 4.7 oops -15.4


:-) 2.8 @#*($&

24
Solution: Version 3
// Displays each number in the given file,
// and displays their sum at the end.

import java.io.*; // for File, FileNotFoundException


import java.util.*; // for Scanner

public class Echo3 {


public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("numbers.dat"));
double sum = 0.0;
while (input.hasNext()) {
if (input.hasNextDouble()) {
double next = input.nextDouble();
System.out.println("number = " + next);
sum += next;
} else {
input.next(); // consume / throw away bad token
}
}
System.out.println("Sum = " + sum);
}
}

25
Line-based processing

26
Who's next in line?

 Reading a file line-by-line, general syntax:

Scanner input = new Scanner(new File("<file name>"));


while (input.hasNextLine()) {
String line = input.nextLine();
<process this line>;
}

 The nextLine method returns the characters from


the input cursor's current position to the nearest \n
character.

27
Reading between the newlines

23 3.14 John Smith "Hello world"


45.2 19

23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n

 input.nextLine()
23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n
^

 input.nextLine()
23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n
^

 NB: The \n character is consumed but not returned.


28
Exercise
 Write a program that reads a text file and "quotes" it by putting a > in
front of each line.

Input:
Hey Prof. Yates,
I would like to know more about files. Please explain them to me.
Sincerely,
Susie Q. Student

Output:
> Hey Prof. Yates,
> I would like to know more about files. Please explain them to me.
> Sincerely,
> Susie Q. Student

29
Solution
import java.io.*;
import java.util.*;

public class QuoteMessage {


public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("message.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(">" + line);
}
}
}

30
Example

 Example file contents:

123 Susan 12.5 8.1 7.6 3.2


456 Brad 4.0 11.6 6.5 2.7 12
789 Jennifer 8.0 8.0 8.0 8.0 7.5

 Consider the task of computing the total hours worked


for each person represented in the above file.

Susan (ID#123) worked 31.4 hours (7.85 hours/day)


Brad (ID#456) worked 36.8 hours (7.36 hours/day)
Jennifer (ID#789) worked 39.5 hours (7.9 hours/day)

31
Line-based or token-based?

 Neither line-based nor token-based processing


works.

 The better solution is a hybrid approach


 Break the input into lines.
 Break each line into tokens.

32
Scanners on Strings
 A Scanner can be constructed to tokenize a particular
String (such as one line of an input file).

Scanner <name> = new Scanner(<String>);

 Example:
String text = "1.4 3.2 hello 9 27.5";
Scanner scan = new Scanner(text); // five tokens

33
Tokenizing lines

Scanner input = new Scanner(new File("<file name>"));


while (input.hasNextLine()) {
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
<process this line>;
}

34
Multi-line records

 The following data represents students' course information.

Erica Kane
3 2.8 4 3.9 3 3.1
Greenlee Smythe
3 3.9 3 4.0 4 3.9
Ryan Laveree, Jr.
2 4.0 3 3.6 4 3.8 1 2.8

Each student's record has the following format:


• Name
• Credits Grade Credits Grade Credits Grade ...

 How can we process one or all of these records?


35
File output

36
Outputting text to files

 PrintWriter: A class in the java.io package that


lets you print output to a destination such as a file.
 Setting up an output file, general syntax:
PrintWriter <name> =
new PrintWriter(new File("<file name>"));

 Example:
PrintWriter output = new PrintWriter(new File("output.txt"));
output.println("Hello, file!");
output.println("This is a second line of output.");

37
Common Courtesy

 Your program should close what it has opened!


 Use the close() method to close a file after your done with it.

 Example:
PrintWriter out = new PrintWriter(“output.txt”);
out.println(“Hello, output file!”);
out.close();

 Also works on Scanner objects


 close() releases system resources associated with an
open file.
Solution
public class Copier {
public static void main(String [] args)
throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
String name1 = keyboard.next();
String name2 = keyboard.next();

Scanner input = new Scanner(new File(name1));


PrintWriter output = new PrintWriter(new File(name2));

while (input.hasNextLine()) {
output.println(input.nextLine());
}

input.close();
output.close();
}
}

39
Binary File I/O
Not all files are text files

 Images, videos, mp3s, oh my!

 Let’s say we wanted to write a program that makes a


copy of an mp3 –

Q: What’s wrong with using Scanner and PrintWriter?

A: If the file contains no `\n’ characters, the


nextLine() method will try to read the entire file into
memory all at once!
Binary I/O
Text I/O requires encoding and decoding.
 The JVM converts a Unicode to a file specific encoding when writing a
character and coverts a file specific encoding to a Unicode when
reading a character.
Binary I/O does not require conversions.
 When you write a byte to a file, the original byte is copied into the file.
When you read a byte from a file, the exact byte in the file is returned.

Text I/O program

The Unicode of Encoding/ The encoding of the character


(a) is stored in the file
the character Decoding
e.g. "199" 00110001 00111001 00111001
,
0x31 0x39 0x39

Binary I/O program

(b) A byte is read/written The same byte in the file

e.g. 199 00110111


,
0xC7 42
Binary I/O Classes

FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream

OutputStream FilterOutputStream DataOutputStream

ObjectOutputStream PrintStream

43
Reading binary data from files

 FileInputStream: a class in the java.io package


that lets you read binary data in chunks whose size you
specify.
 Setting up an input file, general syntax:
FileInputStream <name> =
new FileInputStream(new File("<file name>"));
 Example:
FileInputStream input = new FileInputStream(new
File(“input.mp3"));
int nextByte = input.read();
byte [] buffer = new byte[100];
int numBytesRead = input.read(buffer);
Outputting binary data to files

 PrintStream: Another class in the java.io


package that lets you print output to a destination such
as a file.
 Writer: text output, Stream: binary output
 System.out is a PrintStream object!
 Any methods you have used on System.out (such as
print, println) will work on every PrintStream
object.
Setting up the PrintStream

 Setting up an output file, general syntax:


PrintStream <name> =
new PrintStream(new File("<file name>"));

 Example:
PrintStream output = new PrintStream(new File("output.txt"));
output.println("Hello, file!");
output.println("This is a second line of output.");

Or

output.write(buffer, offset, numBytes);

46
PrintStream warning
 Caution: Do not open a file for reading (Scanner)
and writing (PrintStream) at the same time.
 You could overwrite your input file by accident!

47
Exercise

 Write a class named BinaryCopier that reads in


two filenames from the user and copies the binary
contents from the first file into the second file.

48
Solution
public class BinaryCopier {
public static void main(String [] args)
throws FileNotFoundException, IOException
{
Scanner kb = new Scanner(System.in);
String name1 = kb.next();
String name2 = kb.next();
FileInputStream input =
new FileInputStream(new File(name1));
PrintStream output =
new PrintStream(new File(name2));

byte [] buffer = new byte[100];


int numBytesRead = input.read(buffer);

while (numBytesRead > -1) {


output.write(buffer, 0, numBytesRead);
}
input.close();
output.close();
}
}

49
FilterInputStream/FilterOutputStream

FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream

OutputStream FilterOutputStream DataOutputStream

ObjectOutputStream PrintStream

Filter streams are streams that filter bytes for some purpose.
 The basic byte input stream provides a read method that can only be used for
reading bytes.
 If you want to read integers, doubles, or strings, you need a filter class to wrap
the byte input stream. Using a filter class enables you to read integers, doubles,
and strings instead of bytes and characters.
 FilterInputStream and FilterOutputStream are the base classes for filtering data.
When you need to process primitive numeric types, use DatInputStream and
DataOutputStream to filter bytes. 50
DataInputStream/DataOutputStream
DataInputStream reads bytes from the
stream and converts them into appropriate
primitive type values or strings.

FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream

OutputStream FilterOutputStream DataOutputStream

ObjectOutputStream PrintStream

DataOutputStream converts primitive type values or


strings into bytes and output the bytes to the stream.

51
DataInputStream
DataInputStream extends FilterInputStream
and implements the DataInput interface.
InputStream java.io.DataInput

+readBoolean(): boolean Reads a Boolean from the input stream.


+readByte(): byte Reads a byte from the input stream.
FilterInputStream
+readChar(): char Reads a character from the input stream.
+readFloat(): float Reads a float from the input stream.
+readDouble(): float Reads a double from the input stream.
DataInputStream +readInt(): int Reads an int from the input stream.
+DataInputStream( +readLong(): long Reads a long from the input stream.
in: InputStream) +readShort(): short Reads a short from the input stream.
+readLine(): String Reads a line of characters from input.
+readUTF(): String Reads a string in UTF format.

52
BufferedInputStream/BufferedOutputStream
Using buffers to speed up I/O

FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream

OutputStream FilterOutputStream DataOutputStream

ObjectOutputStream PrintStream

– BufferedInputStream/BufferedOutputStream does not contain new methods.


– All the methods BufferedInputStream/BufferedOutputStream are inherited from the
InputStream/OutputStream classes.

53
Object I/O
DataInputStream/DataOutputStream enables you to perform I/O for
primitive type values and strings.
ObjectInputStream/ObjectOutputStream enables you to perform I/O for
objects in addition for primitive type values and strings.

FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream

OutputStream FilterOutputStream DataOutputStream

ObjectOutputStream PrintStream

54
ObjectInputStream
ObjectInputStream extends InputStream and
implements ObjectInput and ObjectStreamConstants.

java.io.InputStream ObjectStreamConstants

java.io.DataInput

java.io.ObjectInputStream java.io.ObjectInput

+ObjectInputStream(in: InputStream) +readObject(): Object Reads an object.

55
ObjectOutputStream
ObjectOutputStream extends OutputStream and
implements ObjectOutput and ObjectStreamConstants.

java.io.OutputStream ObjectStreamConstants

java.io.DataOutput

java.io.ObjectOutputStream java.io.ObjectOutput

+ObjectOutputStream(out: OutputStream) +writeObject(o: Object): void Writes an object.

56
The Serializable Interface
Not all objects can be written to an output stream.
 Objects that can be written to an object stream is said to be serializable.
A serializable object is an instance of the java.io.Serializable interface.
So the class of a serializable object must implement Serializable.

The Serializable interface is a marker interface.


 It has no methods, so you don't need to add additional code in your
class that implements Serializable.

Implementing this interface enables the Java serialization


mechanism to automate the process of storing the objects and
arrays.

57
The transient Keyword
 If an object is an instance of Serializable, but it
contains non-serializable instance data fields, can the
object be serialized?
 The answer is no.
 To enable the object to be serialized, you can use
the transient keyword to mark these data fields to tell
the JVM to ignore these fields when writing the object
to an object stream.

58
The transient Keyword, cont.
Consider the following class:
 
public class Foo implements java.io.Serializable {
private int v1;
private static double v2;
private transient A v3 = new A();
}
class A { } // A is not serializable
 
When an object of the Foo class is serialized, only variable v1
is serialized. Variable v2 is not serialized because it is a static
variable, and variable v3 is not serialized because it is marked
transient. If v3 were not marked transient, a
java.io.NotSerializableException would occur.

59
Random Access Files
All of the streams you have used so far are known as
read-only or write-only streams.
The external files of these streams are sequential files
that cannot be updated without creating a new file.
It is often necessary to modify files or to insert new
records into files. Java provides the RandomAccessFile
class to allow a file to be read from and write to at random
locations.

60
RandomAccessFile

DataInput DataInput

java.io.RandomAccessFile

+RandomAccessFile(file: File, mode: Creates a RandomAccessFile stream with the specified File object and
String) mode.
+RandomAccessFile(name: String, Creates a RandomAccessFile stream with the specified file name
mode: String) string and mode.
+close(): void Closes the stream and releases the resource associated with the stream.
+getFilePointer(): long Returns the offset, in bytes, from the beginning of the file to where the
next read or write occurs.
+length(): long Returns the length of this file.
+read(): int Reads a byte of data from this file and returns –1 an the end of stream.
+read(b: byte[]): int Reads up to b.length bytes of data from this file into an array of bytes.
+read(b: byte[], off: int, len: int) : int Reads up to len bytes of data from this file into an array of bytes.
+seek(long pos): void Sets the offset (in bytes specified in pos) from the beginning of the
stream to where the next read or write occurs.
+setLength(newLength: long): void Sets a new length of this file.
+skipBytes(int n): int Skips over n bytes of input discarding the skipped bytes.
+write(b: byte[]): void Writes b.length bytes from the specified byte array to this file, starting
+write(byte b[], int off, int len) at the current file pointer.
+write(b: byte[], off: int, len: int): Writes len bytes from the specified byte array starting at offset off to
void this file.

61
RandomAccessFile Methods

Many methods in RandomAccessFile are the same as


those in DataInputStream and DataOutputStream.
 For example, readInt(), readLong(), writeDouble(),
readLine(), writeInt(), and writeLong() can be used in
data input stream or data output stream as well as in
RandomAccessFile streams.

62
RandomAccessFile Methods, cont.
 void seek(long pos) throws IOException;
Sets the offset from the beginning of the
RandomAccessFile stream to where the next read
or write occurs.

 long getFilePointer() IOException;


Returns the current offset, in bytes, from the
beginning of the file to where the next read
or write occurs.

63
RandomAccessFile Methods, cont.
 long length()IOException
Returns the length of the file.

 final void writeChar(int v) throws


IOException
Writes a character to the file as a two-byte
Unicode, with the high byte written first.

 final void writeChars(String s)


throws IOException
Writes a string to the file as a sequence of
characters.
64

You might also like