CPS 209 Lecture 4: Lecture 4 I O Streams

72 views9 pages
Lecture 4: I/O Streams
lecture
Files used:
4.1. Streams and their decorators
2 stream classes in Java:
InputStream
OutputStream
these model an underlying mechanism:
to move raw unsigned bytes from point A (sender) to point B (receiver).
What do their subclasses represent?
concrete implementations for different A and B
//newRandom(12345) where 12345 is a seed
//newRandom()
// An implementation of Algorithm B from TAOCP 2,
// "Seminumerical Algorithms" by Donald E. Knuth,
// as a decorator that can be put in front of any
// object of type Random. (Yes, even itself.)
import java.util.Random;
public class RandomMixer extends Random {
private int[] values;
private Random rng;
public RandomMixer(Random rng, int k) { //decorator
this.rng = rng;
this.values = new int[k];
for(int i = 0; i < k; i++) { // Prime the pump with first k values
values[i] = rng.nextInt();
}
}
// As per documentation of Random, this method should be
// overridden in subclasses, as the other methods use this
// method internally to produce their results. (This is an
// example of the Template Method design pattern.)
@Override public int next(int bits) {
// Choose a slot to take the result from...
int j = rng.nextInt() % values.length;
if(j < 0) { j = -j; }
int result = values[j];
// and read a new value into that slot
values[j] = rng.nextInt();
return result;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Unlock document

This preview shows pages 1-3 of the document.
Unlock all 9 pages and 3 million more documents.

Already have an account? Log in
At the stream level:
What is the form of the transmitted data?
raw unsigned bytes
this stream moves these bytes without caring what they “mean”
every stream in Java is unidirectional (from sender to receiver)
How would you perform bidirectional communication?
eg: over a TCP/IP socket connection
you have to establish 2 separate streams to opposite directions
What happens to the data when the receiver is busy?
the bytes do not disappear
the stream internally buffers the data until the receiver is ready to read them
What happens if the receiver tries to read data before the sender has sent it?
read method blocks until more bytes become available
or if there is an indication of reaching the end of the stream
What are the parameters read in by the InputStream and OutputStream methods?
int parameters
bc these are easily represent and store all values for signed and unsigned bytes
this is bc the primitive type byte in Java is a signed byte
has a range of -128 to +127
whereas a raw unsigned byte:
has a range of 0 to +255
Who closes the stream?
either side — sender or receiver
after which, no transmission is possible through that stream
once the sender closes the stream
receiver receives a -1 at the remaining reads
this indicates that no more data is incoming
Stream for file or internet connection:
should be closed when not in use
best done by:
finally block in try-catch
guarantees that this will happen
in Java 8+
use try-with-resources shorthand
How does the stream hierarchy allow higher-level capabilities?
relies havily on decorators to existing streams
each decorator is written only 1x
works with any underlying stream from the same hierarchy
eg: compression, encryption, data filtering or checksum calculation
What speeds up streams?
internal buffering of data
eg: method flush in OutputStream forces stream to send forward all bytes currently buffered inside it
this is necessary only in a two-way communication
eg: Internet connection
Closing or flushing the stream decorator:
Unlock document

This preview shows pages 1-3 of the document.
Unlock all 9 pages and 3 million more documents.

Already have an account? Log in
will also close or flush the underlying stream.
import java.io.*;
import java.util.zip.*;
public class GZip {
//doesnt need object variabls
private static void gzipFile(String filename) throws IOException { //throws io incase f
ile cannot open
//filename can be relative or abs path name
InputStream i1 = null;
InputStream i2 = null;
OutputStream o = null;
File original = new File(filename);
try {
i1 = new FileInputStream(original);
o = new GZIPOutputStream(new FileOutputStream(filename + ".gz"));
int b = i1.read();
while(b != -1) {
o.write(b); // Read and write bytes in lockstep
b = i1.read();
}
}
finally {
try { if(i1 != null) i1.close(); } catch(Exception e) { }
try { if(o != null) o.close(); } catch(Exception e) { }
}
i1 = null;
try {
//try is exclusive resource here
//acquire resource
//use resource
//finally block
File zipped = new File(filename + ".gz");
if(!(zipped.exists() && zipped.length() > 0)) { return; }
//if you compress empty file, zip file is still somthing other than 0
i1 = new FileInputStream(original); //read original
i2 = new GZIPInputStream(new FileInputStream(zipped)); //read zipped one byte a
t a time, it uncompresses the data being read
int b1, b2; //read two bytes at the same time
do {
b1 = i1.read();
b2 = i2.read();
if(b1 != b2) { return; } //if different, then compression is failure, if co
ntinues then files are identical
} while(b1 > -1);
}
finally {
//finally if acquired, release resource
try { if(i1 != null) i1.close(); } catch(Exception e) { }
try { if(i2 != null) i2.close(); } catch(Exception e) { }
}
// If we get this far without returning, the original can be deleted.
original.delete();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
Unlock document

This preview shows pages 1-3 of the document.
Unlock all 9 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$10 USD/m
Billed $120 USD annually
Homework Help
Class Notes
Textbook Notes
40 Verified Answers
Study Guides
1 Booster Class
Class+
$8 USD/m
Billed $96 USD annually
Homework Help
Class Notes
Textbook Notes
30 Verified Answers
Study Guides
1 Booster Class