io lecture 5. everything is streams … almost in java input/output is mainly stream based in...

33
IO Lecture 5

Post on 21-Dec-2015

222 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

IO

Lecture 5

Page 2: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Everything is streams … almost

In Java Input/Output is mainly stream based In java.io:

• Console I/O

• File I/O

• One Exception: RandomAccessFile not a stream

Raw byte or multi byte characters. Later we will look at java.nio

• “nio”=New IO

Page 3: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

A stream is

…sequential by nature Data is considered to be one contiguous

(one dimensional) group of information from beginning to end.

Page 4: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Dual stream hierarchies in Java

Byte-oriented vs character-oriented• Byte orientation has the longest history

• Internationalization movement induced (during the 90’s) a need for multibyte characters.

Byte-oriented classes• java.io.OutputStream

• java.io.InputStream Character-oriented classes

• java.io.Writer

• java.io.Reader

Page 5: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Stream Trees

Page 6: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Reader Tree

Page 7: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Writer Tree

Page 8: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Byte oriented streams

Read chapter 3. See figure 3-1 p158. A few special streams:•ByteArrayInputStream lets you read an array of

byte as though it were an InputStream object

•SequenceInputStream/-OutputStream makes it possible to concatenate data from two or more InputStream objects into a single stream.

•PipedInputStream/-OutputStream implements one half of a “pipe”. Pipes are very useful when communicating between threads. See also chapter 11.

Page 9: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Character-oriented streams

Most Byte stream classes has a corresponding character stream class.• E.g. FileReader <-> FileInputStreamFileWriter <-> FileOutputStream

Figure 3-9 p177 Adapter classes for Byte oriented data

• E.g. InputStreamReader takes an InputStream object and converts it into a Reader -object.

Page 10: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Commonly Used Readers and Writers

FileReader: read text from files

BufferedReader: wraps around other Readers to get whole lines of text at a time

FileWriter: write files

PrintWriter: println method automatically adds newline and flushes

Page 11: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Common Uses of java.io

Writing to System.out (a PrintStream) Reading from System.in (an InputStream)

public static void main(String[] args) throws IOException {

System.out.println("What's your favorite ice-cream flavor?");

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

String userInput = br.readLine();

System.out.println(userInput + " isn't an ice-cream flavor!");

}

Page 12: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Writing a file The long way to get a writerFileOutputStream fos = new FileOutputStream("test1");OutputStreamWriter writer = new

OutputStreamWriter(fos);

The short way to get a writerFileWriter writer = new FileWriter(fileName);

After getting a writer writer.write("This is a test file.\n");writer.write("Hello World.\n");writer.write("Goodbye World.\n");writer.close();

Page 13: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Reading a file

The long way to get a readerFileInputStream fis = new FileInputStream(fileName);InputStreamReader reader = new InputStreamReader(fis);

The short way to get a readerFileReader reader = new FileReader(fileName);

After getting a readerBufferedReader br = new BufferedReader(reader);String s = br.readLine();while (s != null) { System.out.println(s); s = br.readLine();}reader.close();

Page 14: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

java.nio

New:• Buffer management

• Channels

• File locking

• Memory mapping

Page 15: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

java.nio: Buffers

“Buffer” a well-known concept, but is often home brewed by developers. They are now predefined and performance-optimized. See figure 3-10 p179.• ByteBuffer, CharBuffer, DoubleBuffer,

FloatBuffer, IntBuffer, LongBuffer, MappedByteBuffer, ShortBuffer

Page 16: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

java.nio: Channels

A flexible concept that includes any open connection to a program entity.•DatagramChannel: when working with datagram

sockets (UDP).•SocketChannel: for use with TCP/IP sockets.•FileChannel: for reading, writing, mapping,

manipulating files.•Pipe.SinkChannel/-SourceChannel: for use

with the writable/readable end of a pipe.

• For more info: read code examples in the book or on the web. See figure 3-12 p183.

Page 17: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

java.nio: Memory mapping

MappedByteBuffer• We may map the contents of a file into a

region of memory.

File locking necessary See figure 3-13 p186-187.

Page 18: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Collections

Lecture 5

Page 19: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Programming…

The foundation in programming is connecting well-known algorithms with well-known data structures.

Hopefully the resulting program is easy to maintain.

Page 20: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Three basic interfaces Collection

• The root interface of the collection framework. Set

• Does not allow duplicate elements• May be ordered.• E.g. HashSet, TreeSet, LinkedHashSet.

List• Defines standard behavior for ordered collections (i.e.

sequences).• May contain duplicates.• E.g. LinkedList, ArrayList, Vector, Stack.

Page 21: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Collection traversal You traverse a collection with an “Iterator”, which is a

cursor object. An object that guides you through the collection sequentially. • (hasNext(), next()…)• Very simple, and very safe.• You don’t instantiate an Iterator, by calling some

constructor. You kindly ask for it. (Remember the “Factory” design pattern?)•Iterator it = someCollection.iterator();while (it.hasNext()){ Item I = (Item) it.next();}

• Notice that the it object is declared to implement the Iterator interface. We don’t really know from which class the object is instantiated.

Page 22: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Maps

Does not extend the “Collection” interface Base class for (Key -> value) datatypes Unsorted Map implementations

• E.g. LinkedHashMap, HashMap (fastest),

Sorted implementations• TreeMap,

Page 23: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

The new Collections framework vs the old legacy framework

The new framework of Collection based classes (since Java 2), adopts the Iterator interface.

Older legacy classes use the Enumeration interface, which is similar to Iterator.• Iterator <-> Enumeration:

• iterator() <-> elements()

• hasNext() <-> hasMoreElements()

• next() <-> nextElement()

Page 24: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Thread safety The legacy collections are somewhat thread safe (but not

alltogether) since the methods are fully synchronized (for good and for worse).

The Collections framework is not thread-safe for efficiency reasons.• If multiple threads may access it, the collection may be wrapped in

a readOnlyCollection or synchronizedCollection• Collections.synchronizedCollection(Collection c)

Collections.unmodifiableCollection(Collection c) Iterator is strongly promoted in favour of Enumeration.

• If the collection is modified by another Iterator, you get a ConcurrentModificationException. Iterator is fail-safe. Enumeration is not.

Page 25: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Collections class

Contains wrappers for thread safety. … also contains algorithms

• Sort, shuffle, search, max, min, reverse, rotate, swap.

Page 26: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Observer/Observable

Lecture 5

Page 27: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Observer/Observable examplepublic class IntrusionDetectorextends Observable { private Random rand = new Random(); public void connect(){ if( rand.nextBoolean() ){ // Intrång setChanged(); notifyObservers(); } }}public class SysAdmimplements Observer { private String name; public SysAdm( String name, IntrusionDetector id ) { this.name = name; id.addObserver(this); } public void update( Observable server, Object err ){ System.out.println( name + " förhindrar intrång"); }}

Page 28: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Parsing Strings

Lecture 5

Page 29: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

StringTokenizer

Java.util Break a string into separate tokens

• A token may be a word or a symbol

• Usually a sequence of character not including a whitespace.

• Token delimiter can be specified, and is default set to whitespaces.

Page 30: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Regular expressions

A regular expression is a string of characters that describe a sequence of characters as a pattern.

The pattern is often a mixture of literals and characters with special meaning.• See documentation for “java.util.regex”

• See figure 4-31, 4-32, 4-33, 4-44 p307-308.

Page 31: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

RegExp: Basic steps

1. Create a Pattern object that encapsulates an expression.

2. Acquire a CharSequence object that holds the sequence of characters to test.

3. Get a Matcher object4. Call a method on the Matcher Object.

Find(), matches(), group()

Page 32: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Only two classes in java.util.regex

Pattern Matcher

But regular expressions are rich and worthwhile looking into.

Page 33: IO Lecture 5. Everything is streams … almost In Java Input/Output is mainly stream based In java.io : Console I/O File I/O One Exception: RandomAccessFile

Remember

…to keep an extra eye on the backslashes• In literal Java strings the backslash is an escape

character. The literal string "\\" is a single backslash.

• In regular expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash. This regular expression as a Java string, becomes "\\\\". That's right: 4 backslashes to match a single one.

Test and confirm your belief