Java I/O

Binary Streams (bytes) This document is incomplete!

The two superclasses for binary streams are InputStream and OutputStream.

<== INPUT ==>

FileInputStream

reads data from a file

BufferedInputStream

adds buffering

DataInputStream

adds methods to handle basic data types

File f = new File ("Stuff.dat");
DataInputStream disFile = new DataInputStream( new BufferedInputStream( new FileInputStream (f)));

OR ... omitting the File object

DataInputStream disFile = new DataInputStream( new BufferedInputStream( new FileInputStream ("Stuff.dat")));

<== OUTPUT ==>

FileOutputStream

writes data from a file

BufferedOutputStream

adds buffering

DataOutputStream

adds methods to handle basic data types

File f = new File ("Stuff.dat");
DataOutputStream dosFile = new DataOutputStream( new BufferedOutputStream( new FileOutputStream (f)));

There is a whole lot more about reading and writing from files, appending to a file, making a new one, etc. You can just learn the stuff as you need it.

Example of binary output

File f = new File ("Stuff.dat");
		
try (DataOutputStream dosFile = new DataOutputStream( new BufferedOutputStream( new FileOutputStream (f))) ) {
   for (int i=0; i<256; i++) {
      //dosFile.writeInt(i); //this will write 4 bytes of one integer (so up to 2,147,483,647).
      //dosFile.write(i); //this will only write the lowest 8 bits (i.e. up to 256)
      dosFile.writeByte(i); //this will only write the lowest 8 bits (i.e. up to 256)
   }
} catch (IOException ex) { //this also catches the subclass "FileNotFoundException"
   System.out.println(ex.toString());
} finally {
   System.out.println("This form of TRY automatically closes the FileOutputStream.");
}

To read and write images, use the ImageIO.read() and ImageIO.write() methods.