Download Advanced Java Class

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
Transcript
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)
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
Stream Trees
Reader Tree
Writer Tree
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.
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
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!");
}
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();
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();
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
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