Java I/O

I/O in General

Input and output in Java is complicated, but then it is in many programming languages. As far as this topic is concerned, I/O refers to bytes that are input or output from devices such as the keyboard, the console, files on disk, webpages, etc. We are not using I/O to refer to events that happen in a GUI environment (mouse clicks, mouse movements, typing into a textbox, etc.).

There are at least three different ways of dealing with I/O.

Java I/O - Streams

All of the (stream) classes involved in Java I/O are in the package java.io.* so this must be imported at the beginning of your program.

There are two main types of streams / data:

  1. characters: these are simple ASCII and UniCode characters like what you are reading right now.
  2. binary: this is data that is encoded as bytes / binary. It can't be read unless you know what you are looking for and how it was stored.

For example, this is the first part of a PNG file:

    <89>PNG^M ^Z ^@^@^@^MIHDR^@^@^Fr^@^@^Dø^H^B^@^@^@£nËÄ^@^@^@^CsBIT^H^H^HÛáOà^@^@ ^@IDATx<9c>ì½[¬$YvÖ^_×¼g<9e><93>'Ï¥NUwOwÑ=^^^O3Ã<8c>Ç3ú^K<8c>^Q ^^<90>A^H<81><85>,<81>xàÑ^Rh^P<96><90>ü<80><84><90>^X!xC¼ò<80>ÄE .ób^KÉFB6XØô^L<92>/Í´§«»ª»ªÎ5O^ã^^ñ^?ø¦·<82>ÈÌÈÈÌ<88>È<88>Èï÷P:çTfäÎ}Y{­o¯½·ü<8d>o|ãïý½¿÷^Wÿâ_ìv»R^F^DA Ëòvïõ}_Q<94>T<8a>±öQ¦iÖj5×ukµZä¿^\ÇÑu=<95>bÄc^XF³Ù<

and here is the first part of an MP3 file:

D3^C^@^@^@^@^FTENC^@^@^@^A@^@^@WXXX^@^@^@^B^@^@^@^@TCOP^@^@^@^A^@^@^@TYER^@^@^@^A^@^@^@My PrayerTALB^@^@^@^A^@^@^@COMM ^@^@^@^X^@^@^@eng^@with Andrea BocelliTCON^@^@^@^A^@^@^@ TRCK^@^@^@^A^@^@^@TSSE^@^@4%Órù^?ÿósKPoÿüÞ¢ù}6OÿÿúÓu <81>»<97>?ÿùpÂ<83>^GÖ^_<80>^@^PbZåM<92>±^S^Uô<84>µI<9a>~1ʲíÁØWÿû<92>d^L^Dc*MÙ¿a^@^@;¢ªÜæ ^@^Mi=aL<«É^M^K+(ö à<y%<85>^@<91>Ç2Ô¥Gõ4´ì{^^ÕÒýè3G^Zc©µ^M^QwÄ}Wë2ª´·ßÿÿ^MñÜ^?èË^EÉ0i£<95>Ùçêa¢âïº<84>

We'll be focusing on character streams and only look at binary streams if we have time.

Java IO classes appear complicated ...