![]() |
Java I/O
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 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 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: 29 Sept 2004 ©2002 by Z. Tomaszewski. |