File IO
-
- Basics
- Bytes
- A file is array of bytes.
- How to relate bytes to types
- Streams
- Sequence of bytes
- Basic
- FileOutputStream
- new FileOutputStream(File f)
- new FileOutputStream(String name)
- new FileOutputStream(File f, boolean append)
- new FileOutputStream(String name, boolean append)
- FileInputStream
- Similar to above (without append)
- Network IO handled in similar manner.
- Chaining
- The output of one stream is input to another.
- Typically two levels, but can be more.
- Buffering
- For efficiency, number of bytes handled at same time.
- Eg, Disk written when buffer full, closed, or flushed.
- Eg, Buffered reading allows reading entire line.
- Exceptions
- Must put IO code in try..catch
- FileNotFoundException
- Many others
- Access
- Sequential
- Random or direct
- RandomAccessFile
- Ex: p878 D&D
- File class
- Represents file or directory
- Doesn't do IO
- Can be obtained from JFileChooser
- Can use path/filename
- EX: D&D p 841
- File filters
- javax.swing.JFileChooser.FileFilter
- java.io.FileFilter
- package
- Text
- Encoding
- For characters, use Readers and Writers
- Classes
- BufferedReader
- BufferedWriter
- Primitives
- DatainputStream
- DataOutputStream
- Objects
- Serialization
- Problem: How to you store objects in a file?
- Writes all instance variables.
- Statics not serialized.
- Flattened, marshalled, freeze-dried
- Turns objects into sometime rereadable
- Recursively serialize subobjects
- Class must implement Serializable
- Marker/Tag class
- No methods required
- Serializable is inherited (as usual)
- Object contents
- Primitives
- Other serializable objects
- Objects only saved once regardless num of refs
- 'transient' keyword
- Marks fields not to be written.
- Classes
- Typically chain FileStream to constructor
- ObjectOutputStream
- ObjectInputStream
- Writing
- Open output stream, eg, FileOutputStream
- Create ObjectOutputStream from it.
- Call oos.writeObject(obj)
- Close streams.
- Reading
- Open input stream, eg, FileInputStream
- Create ObjectInputStream
- myObj = (MyType)ois.readObject()
- Close streams
- Example
- Proces
- Find class
- Create object without calling constructor
- If class changes!
- Deserializing after changing class may cause problems
- Bad
- Removing instance variable
- Changing type of variables
- Changing inheritance hierarchy
- Changing anyones Serializable state
- OK
- Addiing instance vars
- Will deserialize to default values.
- includes making non-transient
- Adding subclasses
- Can define serialVersionUID
- Refs
- http://www.sys-con.com/story/?storyid=44199
- Prefs/Props
- Preferences
- prefs = Preferences.userNodeForPackage(this.getClass());
- In registery or wherever
- Key-value pairs
- Properties
- Similar to Preferences
- Reads from a file
- Key-value pairs
- Console
- PrintStream System.out
- PrintStream System.err
- InputStream System.in