1 / 47

CS242 Advanced Programming Concepts in Java

Outline. I/O in Java: binary vs. text dataFile I/Otext files: FileReader, StringTokenizer, Scannerbinary files: StreamReader, StreamWriterReadings: Java Tutorial, Reading ?n WritingOODP: Chapter 5 ? Patterns

fred
Download Presentation

CS242 Advanced Programming Concepts in Java

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. CS242 Advanced Programming Concepts in Java 10/30/07 I/O in Java

    2. Outline I/O in Java: binary vs. text data File I/O text files: FileReader, StringTokenizer, Scanner binary files: StreamReader, StreamWriter Readings: Java Tutorial, Reading ‘n Writing OODP: Chapter 5 – Patterns & GUI Programming HW#5: posted, team (of 2), due: 11/13/07 Review session for Exam#1: Thurs, 11/01, 7:00 pm

    3. Recap: I/O in Java package java.io (also see java.nio) text: Reader, Writer binary: InputStream, OutputStream converting from stream to text: InputStreamReader buffering: BufferedReader package java.util Scanner

    4. Recap: I/O in Java constructors for InputStreamReader include: InputStreamReader( InputStream in ); constructors for BufferedReader include: BufferedReader( Reader rin ); constructors for Scanner include: Scanner( InputStream source ); Scanner( File source ); Scanner( String source );

    5. Recap: I/O in Java Choose one of the abstract classes Wrap functionality around it (buffers, files, compression, etc.) Format, if desired

    6. // Read and echo lines until EOS public static final String EOS = null; try { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); String inLine; while (( inLine = stdin.readLine()) != EOS) System.out.println(inLine); stdin.close(); } catch (IOException e) …

    7. try { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); String inLine = stdin.readLine(); int val = Integer.parseInt(inLine); System.out.println(“Integer value is: “ + val); } catch (NumberFormatException e) { System.err.println(inLine + “ is not an int”); } catch (IOException e) { System.err.println(“Unexpected IO error: “ + e); }

    9. InputStream

    10. OutputStream

    11. Reader

    12. Writer

    13. Writing on standard output System.out.println("Hello" + new Date()); System.out is a PrintStream (OutputStream + ability to print data) doesn't throw Exceptions (can use method checkError() to detect errors) println() method is polymorphic Object, String, int, float, char[], boolean + is polymorphic a + b can mean String concatenation or addition, depending on what a and b are

    14. Writing on standard output println adds the correct end-of-line characters for the target OS \r\n in Windows \n in Unix \r in Mac System.getProperty("line.separator") returns this string of end-of-line characters

    15. // toString revisited public class MyClass { private String myName; public String toString() { return "BadNewline@" + "\n" + myName; } public static void main(String[] args) { MyClass jack = new MyClass("Jack Frost"); System.out.println(jack); }

    16. // toString revisited public class BetterClass { private String myName; public static final String NEWLINE = System.getProperty(“line.separator”); public String toString() { return “GoodNewline@" + NEWLINE + myName; } public static void main(String[] args) { BetterClass jack = new BetterClass("Jack Frost"); System.out.println(jack); }

    17. File I/O: change the data source BufferedReader inData = new BufferedReader( new InputStreamReader(System.in) );

    18. File I/O: change the data source BufferedReader inData = new BufferedReader( new FileReader( “myData.txt”) );

    19. File I/O: Text Files BufferedReader inData = new BufferedReader( new FileReader( “myData.txt”)); or File filePath = new File(“c:\\cs242\\”); BufferedReader inData = new BufferedReader( new FileReader(filePath, “myData.txt”));

    20. FileReader public FileReader(String fileName) throws FileNotFoundException Creates a new FileReader, given the name of the file to read from. Parameters: fileName - the name of the file to read from Throws: FileNotFoundException - if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

    21. try { BufferedReader stdin = new BufferedReader( new FileReader(“myData.txt”));

    22. try { BufferedReader stdin = new BufferedReader( new FileReader(“myData.txt”)); String inLine = stdin.readLine(); int val = Integer.parseInt(inLine); System.out.println(“Integer value is: “ + val);

    23. try { BufferedReader stdin = new BufferedReader( new FileReader(“myData.txt”)); String inLine = stdin.readLine(); int val = Integer.parseInt(inLine); System.out.println(“Integer value is: “ + val); } catch (NumberFormatException e) { System.err.println(inLine + “ is not an int”);

    24. try { BufferedReader stdin = new BufferedReader( new FileReader(“myData.txt”)); String inLine = stdin.readLine(); int val = Integer.parseInt(inLine); System.out.println(“Integer value is: “ + val); } catch (NumberFormatException e) { System.err.println(inLine + “ is not an int”); } catch (FileNotFoundException e) { System.err.println(“Could not open file for reading”);

    25. try { BufferedReader stdin = new BufferedReader( new FileReader(“myData.txt”)); String inLine = stdin.readLine(); int val = Integer.parseInt(inLine); System.out.println(“Integer value is: “ + val); } catch (NumberFormatException e) { System.err.println(inLine + “ is not an int”); } catch (FileNotFoundException e) { System.err.println(“Could not open file for reading”); } catch (IOException e) { System.err.println(“Unexpected IO error: “ + e); }

    26. StringTokenizer (java.util) used to break a String into separate “tokens” public StringTokenizer(String str) Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set, which is " \t\n\r\f": the space character, the tab character, the newline character, the carriage-return character, and the form-feed character. Delimiter characters themselves will not be treated as tokens. public StringTokenizer(String str, String delim)

    27. StringTokenizer public boolean hasMoreTokens() Tests if there are more tokens available from this tokenizer's string. If this method returns true, then a subsequent call to nextToken with no argument will successfully return a token. public String nextToken() Returns the next token from this string tokenizer public int countTokens() Returns the number of tokens

    28. StringTokenizer st = new StringTokenizer("that, that is, is"); while(st.hasMoreTokens()) System.out.println("Token<" + st.nextToken() + “>”); prints Token:<that,> Token:<that> Token:<is,> Token:<is>

    29. StringTokenizer st2 = new StringTokenizer("that, that is, is” , ”,”); while(st2.hasMoreTokens()) System.out.println("Token<" + st2.nextToken() + “>”); prints Token<that> Token< that is> Token< is>

    30. StringTokenizer st3 = new StringTokenizer("that, that| is, is” , ”, |”); while(st3.hasMoreTokens()) System.out.println("Token<" + st3.nextToken() + “>”); prints Token<that> Token<that> Token<is> Token<is>

    31. StringTokenizer: in General StringTokenizer st = new StringTokenizer(<some String>, <delimiters>); while(st.hasMoreTokens()) System.out.println("Token:" + st.nextToken());

    32. StringTokenizer vs. Scanner Java 1.5 introduced a new class: Scanner that makes it easy to read and parse strings and primitive types using regular expressions (class java.util.regex.Pattern) constructors include: Scanner( File pathname ); Scanner( InputStream is ); Scanner( String aLine ); cf: http://java.sun.com/developer/JDCTechTips/2005/tt0308.html#2

    33. Regular Expressions

    34. // Read and echo lines, using BufferedReader public static final String EOS = null; try { BufferedReader stdin = new BufferedReader( new FileReader(“MyData.txt”)); String inLine; while (( inLine = stdin.readLine()) != EOS) System.out.println(inLine); stdin.close(); } catch (IOException e) {…

    35. // Read and echo tokens, using Scanner import java.util.*; try { Scanner scan = new Scanner( new File(“MyData.txt”)); while ( scan.hasNext() ) System.out.println( scan.next() ); scan.close(); } catch (IOException e) {…

    36. // Read and echo lines, using Scanner import java.util.*; try { Scanner scan = new Scanner( new File(“MyData.txt”)); scan.useDelimiter( System.getProperty(“line.separator”)); while ( scan.hasNext() ) System.out.println( scan.next() ); scan.close(); } catch (IOException e) {…

    37. try { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); String inLine = stdin.readLine(); int val = Integer.parseInt(inLine); System.out.println(“Integer value is: “ + val); } catch (NumberFormatException e) { System.err.println(inLine + “ is not an int”); } catch (IOException e) { System.err.println(“Unexpected IO error: “ + e); }

    38. try { Scanner scan = new Scanner( System.in ); int val = scan.nextInt(); System.out.println(“Integer value is: “ + val); } catch (InputMismatchException e) { System.err.println(“Did not input an int”); }

    39. try { BufferedReader stdin = new BufferedReader( new FileReader(“sample.txt”)); String inLine = stdin.readLine(); int val = Integer.parseInt(inLine); System.out.println(“Integer value is: “ + val); } catch (NumberFormatException e) { System.err.println(inLine + “ is not an int”); } catch (FileNotFoundException e) { System.err.println(“Could not open file for reading”); } catch (IOException e) { System.err.println(“Unexpected IO error: “ + e); }

    40. try { Scanner scan = new Scanner( new File(“sample.txt”)); int val = scan.nextInt(); System.out.println(“Integer value is: “ + val); } catch (InputMismatchException e) { System.err.println(“Next token is not an int”); } catch (FileNotFoundException e) { System.err.println(“Could not open file for reading”); } catch (IOException e) { System.err.println(“Unexpected IO error: “ + e); }

    41. Suppose a line of input is: <name>|<height> e.g. String line = “Adam|77.2”; Stringtokenizer st = new StringTokenizer(line,”|”); try { String name = st.nextToken(); String token = st.nextToken(); float height = Float.parseFloat(token); System.out.println( name + “ is “ + height + “ inches tall”); } catch …

    42. Suppose a line of input is: <name>|<height> e.g. String line = “Adam|77.2”; Scanner scan = new Scanner(line); scan.useDelimiter(“\\|”); try { String name = scan.next(); float height = scan.nextFloat(); System.out.println( name + “ is “ + height + “ inches tall.”); } catch(InputMismatchException e) …

    43. Suppose a line of input is: Adam|77.2 try { StreamTokenizer stoken = new StreamTokenizer( … ); stoken.ordinaryChar(“|”); // | is a single-char token stoken.nextToken(); // first token is name String name = stoken.sval; stoken.nextToken(); // ignore the second token, | stoken.nextToken(); // third token is height float f = (float) stoken.nval; // nval is a double } catch …

    44. Timer Class The Timer class in javax.swing generates a sequence of action event at specified intervals (OODP, p. 157) ActionListener listen = ....; final int DELAY = 1000; // in ms (1 sec delay) Timer t = new Timer(DELAY, listen); t.start(); // starts the timer

    45. Timer Class ActionListener listen = new ActionListener() { public void actionPerformed(ActionEvent evt) { // do something } };

    46. Observer Design Pattern (OODP, p. 180) shows how an object can tell other objects about events relates to the MVC architecture: model – data (only one model) view – objects which display the visual part of the data (can have multiple views) controller – object that processes user interaction with a view (one controller per view)

    47. Observer Design Pattern (OODP, p. 180) key idea: minimize the coupling between the model, views and controllers a controller detects user interaction that changes the data that controller must tell model about the change the model must notify all views of that change all views must repaint() themselves during painting, each view asks the model for the current data to display model – only knows that views exist and they need to be notified views – don’t know anything about the controllers (so easy to add more views to a model) controller – easy to change the controller for a view

More Related