Java input and output is accomplished using the classes in the
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 file.
Writing to the Screen
You already know how to do this--just write to System.out:
System.out.print("Text to the screen.");
Reading User Input from the Keyboard
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
Reading from a file
BufferedReader filein = new BufferedReader(new FileReader("samplefile.txt"));
Writing to a file
PrintWriter fileout = new PrintWriter(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.
Both of these example programs also show how to process command line arguments.
|~ztomasze Index :
TA Details: ICS211: Java I/O
|Last Edited: 29 Sept 2004|
©2002 by Z. Tomaszewski.