Input and Output in Java Thursday, Jan 19, 2012 Nancy L. Harris
Reference for this topic Java Tutorials I/O CS239 – Spring 2012 1/20/2012
Pictorial view of data streams (from the Java tutorial)
What can we read and write? Bytes – used for binary data, sounds, pictures Characters – used for textual data We will focus on character data
What does a “stream” look like It is not organized as we are used to looking at a “file”. It is conceptually an infinitely long series of bytes. Some readers deal with those bytes as text characters. And each format item (new lines, tabs, spaces) have a corresponding character representation.
What’s a file? A “file” can be thought of as a named bunch of sequential data. That data can be binary (like executable programs) or it can be textual (like the source files you make with JGrasp). Text files are still binary, but their data can be directly interpreted as characters from the Unicode character set.
Processing a file To read from a file To write to a file Open the file Read its data Close the file To write to a file Write its data
Java supports Input File class Scanner class Output Printwriter class CS239 – Spring 2011 8 1/20/2011
Making a copy of a file Involves reading from a source and writing to a target. Demo Note: File I/O requires the handling of “checked” exceptions. These exceptions must be handled or re-thrown.
A note about whitespace Scanner automatically uses “whitespace” to parse input. We can force it to use something else by the useDelimiter() method. Scanner can process: standard input (System.in) files lines of text It’s process of reading individual elements is also called parsing or tokenizing. CS239 – Spring 2011 10
StringTokenizer Class which is also designed to parse a String of data (like a line of text). It can use different delimiters. We then need to use parseInt or parseDouble to make sense of numeric data. CS239 – Spring 2011 11 1/20/2011