Input/Output: Binary Data

Dr Andy Evans

[Fullscreen]

Byte streams

  • InputStream
    Read methods return -1 at the end of the resource.
  • FileInputStream(File fileObject)
    Allows us to read bytes from a file.
  • OutputStream
    Used to write to resources.
  • FileOutputStream(File fileObject)
    Used to write to a file if the user has permission.
    Overwrites old material in file.
  • FileOutputStream(File fileObject, boolean append)
    Only overwrites if append is false.

Example

	
FileInputStream ourStream = null;
File f = new File("e:/myFile.bin");
try {
    ourStream = new FileInputStream(f); 
} catch (FileNotFoundException fnfe) {
    // Do something.
}

The Stream is then usually used in the following fashion...
	
int c = 0;
while( (c = ourStream.read())  >= 0 ) { 
    // Add c to a byte array 
    // (more on this shortly).
}
ourStream.close();

Byte streams II

  • There are cases where we want to write to and from arrays using streams.
  • These are usually used as a convenient way of reading and writing a byte array from other streams and over the network:
    	
    ByteArrayInputStream 
    ByteArrayOutputStream
    
    

Example

	
FileInputStream fin = new FileInputStream(file);
ByteArrayOutputStream baos = new 				 
                ByteArrayOutputStream();

int c; 
while((c = fin.read()) >= 0) { 
    baos.write(c); 
}	
	
byte[] b = baos.toByteArray(); 

  • Saves us having to find out size of byte array as ByteArrayOutputStream has a toByteArray() method.

Buffering streams

  • As with the FileReader/FileWriter:
    	
    BufferedInputStream
    BufferedOutputStream 
    
    
  • You wrap the classes using the buffer's constructors.

Other byte streams

  • RandomAccessFile
    • Used for reading and writing to files when you need to write into the middle of files as opposed to the end.
  • PrintStream
    • Was used in Java 1.0 to write characters, but didn't do a very good job of it.
    • Now deprecated as an object, with the exception of System.out, which is a static final object of this type.
  • Object Streams

Serialization

  • Given that we can read and write bytes to streams, there's nothing to stop us writing objects themselves from the memory to a stream.
  • This lets us transmit objects across the network and save the state of objects in files.
  • This is known as object serialization: more details.

Summary

  • We can represent and explore the files on a machine with the File class.
  • To save us having to understand how external info is produced, java uses streams.
    • We can read and write bytes to files or arrays.
    • We can store or send objects using streams.
    • We can read and write characters to files or arrays.
  • We should always try and use buffers around our streams to ensure access.
  • We should always prepare for a file not being there.