Professional Documents
Culture Documents
Overview
Java I/O
The java.io package Streams, Readers and Writers
Files
Working with Files
URLs
Working with Internet Resources
Results in large inheritance hierarchy, with separate trees for input and output stream classes
Classes for character I/O are called Readers and Writers Why have specialised classes?
To support foreign languages
Unicode
Each character in the ASCII character set fits into a single byte
but thats not enough for chinese, and other complex alphabets Need more than a single byte A Java character (char) is 2 bytes
Using Readers
Reader in = null; try { Reader inner = new FileReader(c:\\temp\\myfile.txt); in = new BufferedReader(inner); //process file } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (Exception e) {} }
Using Writers
Writer out = null; try { Writer inner = new FileWriter(c:\\temp\\myfile.txt); out = new BufferedWriter(inner); //write data to the file } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); } catch (Exception e) {} }
InputStreamReader
Reads bytes from an InputStream, and turns them into characters using a character encoding
OutputStreamWriter
Turns characters sent to the Writer into bytes written by the OutputStream, again using a character encoding.
Check whether the File corresponds to a directory or a file with isDirectory() Well-featured, and intuitive
Take a look through the javadocs
Quick example
Makes it very simple to retrieve files from the Internet. Throws MalformedURLException if you provide an illegal internet address in its constructor Example