1 / 18

159.331 Programming Languages & Algorithms

159.331 Programming Languages & Algorithms. Lecture 17 - Java Programming - Parts 7 & 8. 7. Java I/O. I/O in Java Stream Classes Streams vs Readers Files Read/Write Example Serialization Examples. Java uses streams to handle byte and character I/O

claire
Download Presentation

159.331 Programming Languages & Algorithms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 159.331 Programming Languages & Algorithms Lecture 17 - Java Programming - Parts 7 & 8 Prog Lang & Alg

  2. 7. Java I/O • I/O in Java • Stream Classes • Streams vs Readers • Files • Read/Write Example • Serialization Examples Prog Lang & Alg

  3. Java uses streams to handle byte and character I/O A stream is an ordered source of or destination for bytes. Java library includes pre-defined streams for dealing with common I/O operations cin or stdin - System.in cout or stdout - System.out cerr or stderr - System.err all streams information is contained in the java.io package Streams can be connected to one another or to files Input stream methods int read() int read(byte[]) int read(byte[], int, int) close() int available() skip(long) boolean markSupported() mark(int) reset() Output stream methods write(int) write(byte[]) write(byte[], int, int) close() flush() Java I/O Style Prog Lang & Alg

  4. Stream Classes BufferedInputStream and BufferedOutputStream DataInputStream and DataOutputStream PipedInputStream and PipedOutputStream URL Input Streams Streams vs. Readers Streams are used for reading/writing ints/chars. Readers/Writers are used for 16-bit Unicode characters. Readers/Writers are in the java.io package. Most important stream class: InputStreamReader and OutputStreamWriter. Local character encoding for English-speaking world is 8859_1 User can specify non-local character encodings when constructing the Reader/Writer Prog Lang & Alg

  5. Java Files and I/O Files and directories are represented in Java by the File class. The File class contains information about the file/directory The File object can point to an absolute or relative directory. The file separator is different depending on your platform (Unix, Microsoft Windows, etc.) Java represents this by the static String separator in the java.io.File class File methods: long lastModified() long length() boolean delete() boolean exists() boolean canRead() boolean canWrite() boolean isFile() boolean isDirectory() boolean isAbsolute() String getName() String getPath() String getAbsolutePath() String getParent() boolean renameTo(File) Prog Lang & Alg

  6. import java.util.*; import java.io.*; public class ReadWrite{ public static void main( String args[] ) { try{ FileOutputStream f = new FileOutputStream("myfile.txt"); OutputStreamWriter osw = new OutputStreamWriter(f); BufferedWriter bw = new BufferedWriter(osw); bw.write("This is some text\n"); bw.write("second line\n"); bw.write("and third line\n"); bw.close(); osw.close(); f.close(); } catch(FileNotFoundException ef){ System.out.println("Could not open file"); } catch(IOException ei){ ei.printStackTrace(); } try{ FileInputStream f = new FileInputStream("myfile.txt"); InputStreamReader osr = new InputStreamReader(f); BufferedReader br = new BufferedReader(osr); String s; int i=0; while( (s = br.readLine()) != null ){ System.out.println("Line " + ++i + ":" + s ); } br.close(); osr.close(); f.close(); } catch(FileNotFoundException ef){ System.out.println("Could not open file"); } catch(IOException ei){ ei.printStackTrace(); } } } Read / Write Example Note use of try-catch Example Output: > java ReadWrite Line 1:This is some text Line 2:second line Line 3:and third line > Prog Lang & Alg

  7. import java.util.*; import java.io.*; public class Serialize{ public static void main( String args[] ) { Wrapper w; try{ FileInputStream f = new FileInputStream("myfile.ser"); ObjectInputStream s = new ObjectInputStream(f); w = (Wrapper)s.readObject(); System.out.println("Read Wrapper stamped: " + w.timestamp ); s.close(); f.close(); } catch(FileNotFoundException ef){ System.out.println("Could not open file"); } catch(IOException ei){ ei.printStackTrace(); } catch(ClassNotFoundException ec){ System.out.println("Could not extract Wrapper from myfile.ser"); } w = new Wrapper(); System.out.println("New Wrapper stamped: " + w.timestamp ); try{ FileOutputStream f = new FileOutputStream("myfile.ser"); ObjectOutputStream s = new ObjectOutputStream(f); s.writeObject(w); s.close(); f.close(); } catch(FileNotFoundException ef){ System.out.println("Could not open file"); } catch(IOException ei){ ei.printStackTrace(); } } } class Wrapper implements Serializable{ public Date timestamp; public int someotherdata = 42; Wrapper(){ timestamp = new Date(); } } Serialization Example persistent objects of a sort save to file or squirt down a network link Example Output: > rm myfile.ser > java Serialize Could not open file New Wrapper stamped: Tue Jan 12 07:54:47 GMT+10:30 1999 > java Serialize Read Wrapper stamped: Tue Jan 12 07:54:47 GMT+10:30 1999 New Wrapper stamped: Tue Jan 12 07:54:50 GMT+10:30 1999 > java Serialize Read Wrapper stamped: Tue Jan 12 07:54:50 GMT+10:30 1999 New Wrapper stamped: Tue Jan 12 07:54:53 GMT+10:30 1999 > Prog Lang & Alg

  8. 7. Exercises • Create a Java application called Viewer that can display the contents of any text file. The user should specify the file on the command line, using either a relative path or absolute path. • Create a Java application to copy a text file to a new file with a different name. • Modify the driver program you wrote in a previous section so that it has the ability to serialize and save the People array. • Add to your driver the ability to read in an existing database file and print out the contents. • Add a text-based menu system to your driver program giving the user options to load/save database files, and to add/search database entries. Prog Lang & Alg

  9. Java I/O is done using Streams and with Readers and Writers System.in/out etc Serialization is built into the Java language see transient keyword Streams are interoperable and can be stacked on top of one another to achieve desired user functionality See java.io package Summary Prog Lang & Alg

  10. 8. Java Advanced Data Structures • java.util package • Use of abstract data types • Linked List example • HashTable example • Like the C++ STL - only more powerful and more extensive Prog Lang & Alg

  11. java.util package A Java library containing useful functions for storing dynamic arrays and for storing arrays with efficient access Unlike C++ STL generics, the Java containers can contain any Object - (all objects in Java descend from java.lang.Object) java.util.Vector is a variable-sized array. Vector has a default size. Can store any object type When it reaches its capacity, the size is incremented by a set amount Accessor methods exist to search/add/delete elements. java.util.HashTable implements efficient storage Stores elements according to their hashCode (a property of java.lang.Object inherited by all objects) Prog Lang & Alg

  12. public class LinkedList { public interface Linkable { public Linkable getNext(); // Returns next element in the list public void setNext(Linkable node); // Sets the next element in the list } Linkable head; // head of the linked list public synchronized Linkable getHead(){ return head; } public synchronized void insertAtHead(Linkable node) { node.setNext(head); head = node; } public synchronized void insertAtTail(Linkable node) { if (head == null) head = node; else { Linkable p, q; for(p = head; (q = p.getNext()) != null; p = q); p.setNext(node); } } public synchronized Linkable removeFromHead() { Linkable node = head; if (node != null) { head = node.getNext(); node.setNext(null); } return node; } public synchronized Linkable removeFromTail() { if (head == null) return null; Linkable p = head, q = null, next = head.getNext(); if (next == null) { head = null; return p; } while((next = p.getNext()) != null) { q = p; p = next; } q.setNext(null); return p; } public synchronized void remove(Linkable node) { if (head == null) return; if (node.equals(head)) { head = head.getNext(); return; } Linkable p = head, q = null; while((q = p.getNext()) != null) { if (node.equals(q)) { p.setNext(q.getNext()); return; } p = q; } } Prog Lang & Alg

  13. public static class Test { static class LinkableInteger implements Linkable { int i; // The data contained in the node Linkable next; // A reference to the next node in the list public LinkableInteger(int i) { this.i = i; } // Constructor method public Linkable getNext() { return next; } // Part of Linkable public void setNext(Linkable node) { next = node; }// Part of Linkable public String toString() { return i + ""; } // For easy printing public boolean equals(Object o) { // For comparison if (this == o) return true; if (!(o instanceof LinkableInteger)) return false; if (((LinkableInteger)o).i == this.i) return true; return false; } } /** * The test program. Insert some nodes, remove some nodes, then * print out all elements in the list. It should print out the * numbers 4, 6, 3, 1, and 5 **/ public static void main(String[] args) { LinkedList ll = new LinkedList(); // Create a list ll.insertAtHead(new LinkableInteger(1)); // Insert some stuff ll.insertAtHead(new LinkableInteger(2)); ll.insertAtHead(new LinkableInteger(3)); ll.insertAtHead(new LinkableInteger(4)); ll.insertAtTail(new LinkableInteger(5)); // Insert some more stuff ll.insertAtTail(new LinkableInteger(6)); System.out.println(ll.removeFromHead()); // Remove and print a node System.out.println(ll.removeFromTail()); // Remove and print another ll.remove(new LinkableInteger(2)); // Remove another one // Now print out the contents of the list. for(Linkable l = ll.getHead(); l != null; l = l.getNext()) System.out.println(l); } } } Linked List Example linkable objects example note filename mangling done for inner classes > java LinkedList$Test 4 6 3 1 5 > Prog Lang & Alg

  14. HashTable Example • hashtable worked example code • note use of HashObject as data structure • note use of dedicated exception handler • integrated test method • order of tests important to avoid nullPointerException • use java.util.HashTable for real applications • evolution of the language - deprecation - see example Prog Lang & Alg

  15. // // Hash table Example Program // class HashObject{ // data structure for holding list of key/value pairs String key; Object data; HashObject next; } class NoSuchKeyException extends Exception{ // exception handler public NoSuchKeyException( String s ){ super( s ); } public NoSuchKeyException(){ super(); } } public class HashTable{ // working class plus the test main method private HashObject table[]; private int size; private int rehashSize; private int capacityIncrement; private int count; public HashTable(){ table = new HashObject[23]; size = table.length; rehashSize = 4; capacityIncrement = 2; count = 0; } public void put( String key, Object data ){ HashObject obj = new HashObject(); obj.key = key; obj.data = data; obj.next = null; bucketAdd( table, getBucket(hashCode(key)), obj); count++; if( count > size * rehashSize ){ rehash(); } } public Object get( String key ) throws NoSuchKeyException { HashObject place = table[ getBucket( hashCode(key) ) ]; while( place != null && place.key.compareTo(key) != 0 ){ // note order place = place.next; } if( place == null ){ throw new NoSuchKeyException( key ); } return place.data; } public int hashCode( String key ){ int value = 0; byte keyBytes[] = new byte[key.length()]; key.getBytes( 0, key.length(), keyBytes, 0 ); for( int i = 0; i<keyBytes.length; i++){ value += (int)keyBytes[i]; } return value; } Prog Lang & Alg

  16. private int getBucket( int hash ){ return hash % size; } private void bucketAdd( HashObject table[], int bucket, HashObject obj ){ obj.next = table[ bucket ]; table[bucket] = obj; } private void rehash(){ int newSize = size * capacityIncrement; HashObject newTable[]; HashObject tmp, obj; if( newSize % 2 == 0 ){ newSize++; } newTable = new HashObject[newSize]; for(int i = 0; i< size; i++){ tmp = table[i]; while( tmp != null ){ obj = new HashObject(); obj.key = tmp.key; obj.data = tmp.data; obj.next = null; bucketAdd( newTable, hashCode(tmp.key) % newSize, obj ); tmp = tmp.next; } } size = newSize; table = newTable; } public static void main( String args[] ){ // main method for test code HashTable table = new HashTable(); for(int i = 0; i<5; i++){ table.put("STRING " + i, new Integer(i) ); } for(int i=10; i>=0; i--){ try{ System.out.println("KEY = STRING " + i + " VALUE = " + table.get("STRING " + i ) ); } catch( NoSuchKeyException e ){ System.out.println(" Key Not Found: " + e.getMessage() ); } } } } // end of class HashTable >javac -deprecation HashTable.java HashTable.java:61: Note: The method void getBytes(int, int, byte[], int) in class java.lang.String has been deprecated. key.getBytes( 0, key.length(), keyBytes, 0 ); ^ Note: HashTable.java uses or overrides a deprecated API. Please consult the documentation for a better alternative. 1 warning >java HashTable Key Not Found: STRING 10 Key Not Found: STRING 9 Key Not Found: STRING 8 Key Not Found: STRING 7 Key Not Found: STRING 6 Key Not Found: STRING 5 KEY = STRING 4 VALUE = 4 KEY = STRING 3 VALUE = 3 KEY = STRING 2 VALUE = 2 KEY = STRING 1 VALUE = 1 KEY = STRING 0 VALUE = 0 > Prog Lang & Alg

  17. 8. Exercises • Browse the java.util package • Compare the methods for the various container classes • Consider which you would use to implement a Graph consisting of nodes and edges • How would you implement a Directed Graph where edges have a direction? Prog Lang & Alg

  18. Java comes with a rich library of utilities and container classes The containers can hold any Object The API is growing Track changes on the Java/Sun web sites 8. Summary Prog Lang & Alg

More Related