Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

The java.io Package - Reading and Writing Files

  • FileStreams have three types of constructors
    1. a constructor that takes a filename as a String
    2. a constructor that takes a File object
    3. a constructor that takes a FileDescriptor object
  • when constructors (1) or (2) are used, a new FileDescriptor object is created. This can be accessed by calling getFD()
  • a FileDescriptor object represents a system-dependent value that describes an open file
  • FileOutputStream has one additonal constructor
        FileOutputStream(String name, boolean append)
    
  • if the file exists, you can set append to true to force the write to occur at the end of the file; otherwise, the existing file is overwritten
  • FileOutputStream (and FileWriter) have a flush() method that forces the underlying buffer to be flushed.
Note
  • flush() does NOT guarantee that the contents will be written to disk. To guarantee the data is written to disk use the FileDescriptor method sync()
  • FileReader and FileWriter read and write 16-bit Unicode characters
  • FileInputStream and FileOutputStream read and write bytes

Random Access Files (JPL pg 258)

  • the RandomAccessFile class is NOT a subclass of InputStream, OutputStream, Reader or Writer; instead it incorporates all their functionaly plus additional methods by implementing the DataInput and DataOutput interfaces.
Note
  • You cannot use a RandomAccessFile object where any of the other input and output streams are required.
  • the class has two constructors
        public RandomAccessFile(String name, String mode)
        public RandomAccessFile(File file, String mode)
    
  • the mode argument must be either "r" or "rw" to indicate if the file is to be opened for reading only or reading and writing
  • if the file is opened for writing and it does not exist; it will be created
  • as with the other File streams, a FileDescriptor object is created when the file is opened
  • the class allows you to set a read/write pointer to any position in the file
  • key methods are:
        public long getFilePointer() throws IOException
        public void seek(long pos) throws IOException
        public void skipBytes(int count) throws IOException
        public long length() throws IOException
    

Source code examples



Pkg Overview Data Streams Character Streams Byte Streams File Class Readers & Writers
Filter Streams Data Input/Output Reading & Writing Files Serialization