|
Java I/O
Java input and output is accomplished using the classes in the
InputStreams and OutputStreams deal with bytes. Readers and Writers deal with characters. InputStreamReaders translate bytes to characters for input, and OutputStreamWriters translate characters to bytes for output. Bytes need to be translated into characters (and vice versa) based on a character encoding (such as ANSI, Unicode, etc.), though usually these details are taken care of for you when you just implicitly accept the default encoding. Wrapping a stream (or reader or writer) with a buffer provides for more efficient reading and writing. Wrapping a stream with a PrintStream or PrintWriter means you can use the familiar Between the Java API and Java Tutorial (and maybe a good book), you should be able to familiarize yourself with these different classes in order to know which tools best solve your current problem. However, what follows here are the most commonly-used configurations. The four most common I/O problems you will face are writing to the screen, reading from the keyboard, and reading and writing to a text file. Writing to the ScreenYou already know how to do this--just write to System.out: System.out.print("Text to the screen."); Reading User Input from the KeyboardBufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); Reading from a fileBufferedReader filein = new BufferedReader(new FileReader("samplefile.txt")); Writing to a filePrintWriter fileout = new PrintWriter(new BufferedWriter(new FileWriter("samplefile.txt"));
You can use different variable names for your BufferedReaders and PrintWriters than I have here. Also, you may have code between opening a stream, writing or reading to the stream, and closing the stream. Remember to close any file streams you open. This is especially important when writing to a file, since all your output may not be stored in the file if you forget to It is also possible to use Java streams to read or write to other devices besides the hard disk, or to access resources across a network. We won't be covering such details in this course, but you can learn more from the Java API, the Java Tutorial, or a good book on Java programming. Example Code
Both of these example programs also show how to process command line arguments. |
~ztomasze Index :
TA Details: ICS211: Java I/O http://www2.hawaii.edu/~ztomasze |
Last Edited: 10 Mar 2005 ©2002 by Z. Tomaszewski. |