Download presentation
Presentation is loading. Please wait.
1
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives -> file reading –Keyboard, mouse -> event driven programming –Printers, MIDI boxes, any other hardware Network –Sockets –URLConnection –HTTP Requests (Servlets) –Databases (JDBC)
2
java.io package InputStream Tree – gets bytes OutputStream Tree –sends bytes Reader Tree – wraps around InputStreams to read character data Writer Tree – wraps around OutputStreams to write character data
3
Stream Trees
4
Reader Tree
5
Writer Tree
6
Streams Bytes “flow” a few at a time, not all at once. Should be closed when you’re done with them. The InputStream and Output Stream methods deal with bytes (binary data), not character data. However, some of their subclasses are specialized to deal with character data, just like the Readers and Writers.
7
Commonly Used Readers and Writers FileReader: read text from files BufferedReader: wraps around other Readers to get whole lines of text at a time FileWriter: write files PrintWriter: println method automatically adds newline and flushes
8
Common Uses of java.io Writing to System.out (a PrintStream) Reading from System.in (an InputStream) public static void main(String[] args) throws IOException { System.out.println("What's your favorite ice-cream flavor?"); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String userInput = br.readLine(); System.out.println(userInput + " isn't an ice-cream flavor!"); }
9
Writing a file The long way to get a writer FileOutputStream fos = new FileOutputStream("test1"); OutputStreamWriter writer = new OutputStreamWriter(fos); The short way to get a writer FileWriter writer = new FileWriter(fileName); After getting a writer writer.write("This is a test file.\n"); writer.write("Hello World.\n"); writer.write("Goodbye World.\n"); writer.close();
10
Reading a file The long way to get a reader FileInputStream fis = new FileInputStream(fileName); InputStreamReader reader = new InputStreamReader(fis); The short way to get a reader FileReader reader = new FileReader(fileName); After getting a reader BufferedReader br = new BufferedReader(reader); String s = br.readLine(); while (s != null) { System.out.println(s); s = br.readLine(); } reader.close();
11
New I/O New in Java 1.4 Buffers - so you no longer have to use a byte[] Channels - added functionality, such as file locking
12
I/O mini-task From what you know of the assignments, where and how do you think you will use Java’s I/O classes? Thank you! Next: Network Programming in Java
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.