Upload
lamkhue
View
230
Download
1
Embed Size (px)
Citation preview
3
jonk
v@id
ajo
nkv@
ida
3Streams 1: The Concept A stream: A sequence of elements Made available one at a time Sequential access
Used in most of Java's I/O classes
4
jonk
v@id
ajo
nkv@
ida
4Streams 2: Binary I/O
abstract class InputStream Read a single byte or an array of bytes InputStream is;
Reading from a file is = new FileInputStream("java.dat");
Reading from an array in memory is = new ByteArrayInputStream(…);
Reading from a network socket is = socket.getInputStream();
…
Reading “raw” bytes abstract class OutputStream Write a single byte or an array of bytes OutputStream is;
Writing to a file is = new FileOutputStream("java.dat");
This is how you create an empty file!
Writing to an array in memory is = new ByteArrayOutputStream(…);
Writing to a network socket is = socket.getOutputStream();
…
Writing “raw” bytes
One class for each source / destination
Interfaces would havebeen better – why?
5
jonk
v@id
ajo
nkv@
ida
5Streams 3: Example
A simple OutputStream example:▪ public static void main(String[] args) {
try (OutputStream os = new FileOutputStream("java.dat")) {os.write(3);os.write(new byte[] { 6, 7, 8 });…
} catch (IOException e) {… handle I/O errors that may arise
when opening or using the stream…}
▪ try ( InputStream is = new FileInputStream("foo.dat");OutputStream os = new FileOutputStream("java.dat"))
{…
} catch (IOException e) {… handle it …
}}
Error handling is important!Always make sure that everyfile is closed!
Declare an AutoCloseableresource in try()… (Java 7+)
Use it inside the block…
… and when you exit the block, the resource (file) willautomatically be closed, even ifthere is an exception!
Using two resources…
This is basically all you can do!
6
jonk
v@id
ajo
nkv@
ida
6Stream Filters 1: Introduction
Division of responsibilities ”Basic” streams handle sources and destinations
Filter streams provide additional functionality▪ Add buffering▪ Support other types of data▪ …
Basic Stream
Filter Stream
Filter Stream
Your code
–Very little basic functionality… for a reason!
7
jonk
v@id
ajo
nkv@
ida
7Stream Filters 2: How do they Work? A simple filter stream example:
▪ public class MyOutputStream {private OutputStream out;public MyOutputStream(final OutputStream out) {
this.out = out;}
▪ public void write(byte b) { out.write(b); }public void write(byte[] b) { out.write(b); }…
▪ public void writeShort(short s) {out.write((s & 0xFF00) >> 8);out.write(s & 0xFF);
}…
}▪ try (MyOutputStream out = new MyOutputStream(
new FileOutputStream("foo.dat"))) {…
}
FileOutputStream
MyOutputStream
Your code
…or any other”destination
stream”
8
jonk
v@id
ajo
nkv@
ida
8Stream Filters 3: Output
try (DataOutputStream os =new DataOutputStream(new BufferedOutputStream(new FileOutputStream("java.dat"))))
{os.write(new byte[] { 6, 7, 8 });os.writeLong(1234567890123L);os.writeFloat(2.7f);
} catch (final IOException e) {… handle it …
}
BufferedOutputStream
Buffers I/O:Don't write a single byte at a time…
PrintStream (System.out / err)
print(), println() methodsfor primitive datatypes and Strings
Uses platform character encodingto convert chars bytes
DataOutputStream writeLong(), writeFloat(), …
writeUTF() – writes UTF-8 format
Useful output filters
9
jonk
v@id
ajo
nkv@
ida
9Stream Filters 4: Input
BufferedInputStream
Buffers I/O:Don't read a single byte at a time…
DataInputStream readLong(), readFloat(), …
readUTF() – reads UTF-8 format
readLine() – deprecated!
Ignores character encodings
Use Readers instead!
Useful input filters
11
jonk
v@id
ajo
nkv@
ida
11Readers and Writers 2 Distinct subsystem for text-based I/O: Reader, Writer Sends full 16-bit Unicode text, not 8-bit bytes
OutputStream
Filter Writer
Filter Writer
Your code
OutputStreamWriter
UTF-8: c3 a4 “ä”ISO Latin-1: c3 a4 “ä”
InputStream
Filter Reader
Filter Reader
Your code
InputStreamReader
Unicode text
Unicode
Unicode
8-bit bytes
Unicode
Unicode
Unicode
8-bit bytesUTF-8: “ä” c3 a4ISO Latin-1: “ä” e4
12
jonk
v@id
ajo
nkv@
ida
12Readers and Writers 3
abstract class Reader Read a single char or an array of chars Reader re;
Reading from a file re = new FileReader("java.dat");
Reading from an array in memory re = new CharArrayReader(…);
re = new StringReader(…);
…
Reading text
abstract class Writer Read a single byte or an array of bytes Writer wr;
Writing to a file wr = new FileWriter("java.dat");
Writing to an array in memory wr = new CharArrayWriter(…);
wr = new StringWriter(…);(writes to a StringBuffer)
…
Writing text
No encoding specified: Use the platform’sdefault to convert bytes chars
So don’t use this for files that should be machine-readable on multiple systems!
13
jonk
v@id
ajo
nkv@
ida
13Readers and Writers 4: Filters
BufferedWriter
Buffers I/O:Don't write a single char at a time…
PrintWriter print(), println() methods
for primitive datatypes and Strings
Text output
Useful filters
BufferedReader
Buffers I/O:Don't read a single char at a time…
Method for reading a line
Text input
14
jonk
v@id
ajo
nkv@
ida
14R/W 5: Specifying Encodings
OutputStream os = new FileOutputStream("file.txt");
Writer wr =new OutputStreamWriter(os, “Big5");
OutputStreamWriterSocket sock = …;InputStream is = sock.getInputStream();Reader re =
new InputStreamReader(is, “Cp1046”);
InputStreamReader
Specify a character encoding using OSW and ISR
FileOutputStream
OutputStreamWriter
Your code
Unicode chars
Bytes in Big5 encoding(Traditional Chinese)
”SocketInputStream”
InputStreamReader
Your code
Unicode chars
Bytes in Cp1046encoding (IBM arabic)
UTF-8 all characters supported, readable on most systems!
16
jonk
v@id
ajo
nkv@
ida
16File[name] Objects: The File Class File Objects (java.io.File) represent file and path names They do not represent open files!
▪ File f = new File("/");File f2 = new File(f, "etc");File f3 = new File(f, "passwd");System.out.print(f3.getAbsolutePath());if (f3.exists()) {
System.out.println("You have a password file");System.out.println("It's in the directory " + f3.getParent());System.out.println("Its length is " + f3.length());if (f3.canRead()) System.out.println("I can read it");if (f3.canWrite()) System.out.println("I can write to it");if (f3.isHidden()) System.out.println("It is hidden");if (f3.delete()) System.out.println("I have deleted it!");try (OutputStream os = new FileOutputStream(f3)) { … };
} Also directory operations:listFiles(), mkdir(),renameTo(), …
Also file system operations:Find available space, total space,file system roots (C:\, D:\),
File.createNewFile() is used for atomic locking – just use a FileOutputStream in most cases!
18
jonk
v@id
ajo
nkv@
ida
18Serialization 1: Intro
OutputStream os = new FileOutputStream("file.dat");
ObjectOutputStream out =new ObjectOutputStream(os);
out.writeObject(gameBoard);out.writeObject(highscoreList);out.close();
ObjectOutputStreamSocket sock = …;InputStream is = sock.getInputStream();ObjectInputStream in =
new ObjectInputStream(is);List<Score> highscoreList =
(List<Score>) in.readObject();in.close();
ObjectInputStream
Serialization: Convert objects to/from sequences of bytes
FileOutputStream
ObjectOutputStream
Your code
Objects
Bytes: All you need toreconstruct the objects
”SocketInputStream”
ObjectInputStream
Your code
Objects
Bytes
Writes an object and
everything it refers to!
19
jonk
v@id
ajo
nkv@
ida
19Serialization 2: Serializable Interface The objects must implement java.io.Serializable An interface without methods, indicating that serialization is allowed
▪ By accessing the byte stream you can read private fields!▪ public class Pair implements Serializable {
private Object first;private Object second;private transient int hashCodeCache;
Pair(Object first, Object second) {this.first = first;this.second = second;
}}
The superclass must:▪ Be Serializable, so we can save its data to the stream, or▪ Have a no-args constructor, so we can reconstruct it from scratch
Many Java classes already implement Serializable▪ Strings, Collections subclasses, …
All fields must also be Serializable!
…except transient fields, whichwe assume can be reconstructed
or are unnecessary for other reasons
20
jonk
v@id
ajo
nkv@
ida
20Serialization 3: Writing An Object Twice
ObjectOutputStream must handle circular references Node structure example:
▪ Node parent = new Node(null);Node child = new Node(parent); // child points to parentparent.addChild(node); // parent points to child
Remembers which objects were written▪ First time: Write object ID + entire object representation▪ Second time: Write object ID
Does not care whether the object was updated!▪ List list = new ArrayList();
oos.write(list); // Writes object ID + entire listlist.add("Another element");oos.write(list); // Writes the object ID…
To write a new copy of the object: Use reset()▪ oos.reset();
21
jonk
v@id
ajo
nkv@
ida
21Serialization 4: Class Versions Can old saved objects be read after changing the class? Some changes are allowed
▪ Adding fields – if you read an old object, the field will be set to 0/null▪ Changing public/protected/private
▪ A few more types of changes
Others are forbidden▪ Changing the class hierarchy in certain ways▪ Removing Serializable
▪ …
You must have the same serial version ID▪ By default this is a hash of certain features in the class — too strict!▪ To allow adding new fields, declare your own version ID:
private final static long serialVersionUID = 1; // for example
▪ IMPORTANT! Change this if you make incompatible changes to your class!
22
jonk
v@id
ajo
nkv@
ida
22Serialization 5: Exceptions Error handling was omitted
▪ ClassNotFoundException – received an object of a non-existing class▪ InvalidClassException▪ StreamCorruptedException – bad control information in the stream▪ OptionalDataException – primitive data found instead of objects▪ NotSerializableException – an object was not Serializable▪ IOException – the usual Input/Output related exceptions
Many more serialization features…▪ http://docs.oracle.com/javase/7/docs/technotes/guides/serialization/index.html
24
jonk
v@id
ajo
nkv@
ida
24Resources 1: Data in the ClassPath How does your program find its image files, audio files, etc? Your software may be installed in different locations Path syntax depends on the OS Your program, including images, can be packed inside a single JAR file
▪ Java ARchive, essentially a ZIP file
Resources reuse the Java class loading mechanism Place files together with your code Use resources to find and load them
Everything in a single JAR file:mypackage/Main.classmypackage/ShowImage.class…data/bin.datimg/test.png
25
jonk
v@id
ajo
nkv@
ida
25Resources 2: Example Since the class loading mechanism is used: Must first have a ClassLoader or a java.lang.Class object
▪ Simplest way: SomeClassInYourProgram.class
Then, getResource() returns a java.net.URL▪ URL url = Main.class.getResource("img/test.png");
Finally:▪ Use the URL's getContent() method to return:▪ an ImageProducer, for images▪ an AudioClip, for audio▪ an InputStream, otherwise
▪ Or construct an ImageIcon from the URL!▪ It calls getContent() for you▪ ImageIcon icon = new ImageIcon(url);
mypackage/Main.classmypackage/ShowImage.class…data/bin.datimg/test.png
Not a file name:”.class” is magic syntax