1 / 34

File and Stream I/O, Redirection Privacy and Super

File and Stream I/O, Redirection Privacy and Super. Talk About Printing. Before talking about input from keyboard, let’s first consider output to screen in Java. System.out.print() is a familiar message. System is a class. Just like Account . System has some fields, one of which is

Télécharger la présentation

File and Stream I/O, Redirection Privacy and Super

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. File and Stream I/O, Redirection Privacy and Super

  2. Talk About Printing • Before talking about input from keyboard, let’s first consider output to screen in Java. • System.out.print() is a familiar message. • System is a class. Just like Account. • System has some fields, one of which is • PrintStream out • out is an object reference to an object of class PrintStream • We further send a print() message to out

  3. Imagine...How Might It Look Like in Java? class System { // public class fields public static PrintStream out; public static InputStream in; // private class field example private static String computerName; // private instance field example private long memoryAvailable; ... }

  4. PrintStream InputStream PrintStream print( ) … print( ) println( ) … println( ) InputStream … … The PictureSystem.out.print() System X out in System.out is a PrintStream object reference. We then send a print() message to this object.

  5. File and Input/Output Operations • There are classes to represent a file on disk, a file in network, or input/ output from console. • They provide methods to make file and IO operations more convenient. • Class PrintStream and Class Scanner

  6. Class PrintStream import java.io.*; ...main(...) throws IOException { PrintStreammyNewFile; myNewFile = new PrintStream("myWeb.txt"); myNewFile.println("Hello World in a file!"); System.out.println("Hello World on screen."); // myNewFile is a PrintStream object reference // System.out is a PrintStream object reference }

  7. PrintStream Object References PrintStream anObjectRef; anObjectRef= System.out; anObjectRef.println("Say Hello to screen!"); anObjectRef= new PrintStream("myWeb.txt"); anObjectRef.println("Say Hello to a file!"); // anObjectRef is a variable. At different time, // it refers to different PrintStream objects: // // System.out is a PrintStream object // new PrintStream() creates another object

  8. PrintStream Object References PrintStream anObjectRef; anObjectRef = System.out; anObjectRef.println("Say Hello to screen! "); PrintStream myNewFile; myNewFile = new PrintStream("myWeb.txt"); anObjectRef = myNewFile; anObjectRef.println("Say Hello to a file! "); // we can copy object references // anObjectRef.println will print differently

  9. Class Scanner import java.util.*; import java.io.*; ...main(...) throws Exception { Scanner markFile; markFile = new Scanner( new File("myWeb.txt") ); int mark; if (markFile.hasNextInt()) mark = markFile.nextInt(); }

  10. Class Scanner • The methods hasNextInt(), hasNextDouble(), hasNextXyz()… return us a boolean (true/ false) value that indicates if there is more data to read from the Scanner object. • The methods nextInt(), nextDouble(), … reads a piece of data from the source for us. • Operations may fail, thus we add “throws Exception” to the main() method.

  11. Class Scanner: line-by-line import java.util.*; import java.io.*; ...main(...) throws Exception { Scanner markFile; markFile = new Scanner( new File("myWeb.txt") ); String aLine; while (markFile.hasNextLine()) { aLine = markFile.nextLine(); System.out.println(aLine); } }

  12. Class Scanner: line-by-line • The method nextLine() reads a line from the source for us. It returns a String. • The source for the Scanner object could be the keyboard, a file, a web source. • System.in is a field in class System. It refers to a default InputStream object, representing the keyboard.

  13. Class Scanner • The source could be • the keyboard object • new Scanner( System.in ); • a file object • new Scanner( new File(“filename”) ); • new Scanner( new URL(“file:///...”).openStream( ) ); • a web source • new Scanner( new URL(“http://...”).openStream( ) );

  14. System Object References • System.out is a class field. • It is an object reference of type PrintStream • It is for outputting text to the console. • System.err is a class field. • It is an object reference of type PrintStream • It is for outputting error messages to the console. • System.in is a class field. • It is an object reference of type InputStream • It is for getting key strokes from the console.

  15. System.out Redirection • System.out.print() / println() sends text to the console screen by default. • It is possible to change this behaviour. • This is called redirection.

  16. Redirecting System.out import java.io.*; class Redirect { public static void main(...) throws IOException { PrintStream myNewFile; myNewFile = new PrintStream("myWeb.html"); System.setOut( myNewFile ); System.out.println("Hello World Web."); // System.out refers to new PrintStream object! } }

  17. PrintStream PrintStream PrintStream print( ) print( ) print( ) println( ) println( ) println( ) Redirect Local variable myNewFile in method main() got a new PrintStream object reference. main( ) myNewFile File [myWeb.html] Object Reference CopyingSystem.out System.out keeps the default PrintStream object reference. Console Screen System X out in

  18. PrintStream PrintStream PrintStream print( ) print( ) print( ) println( ) println( ) println( ) Redirect main( ) myNewFile Object Reference CopyingSystem.out Console Screen System X out in Message System.setOut(myNewFile) changes the field System.out by object reference copying! File [myWeb.html]

  19. System Object References • System.setOut(someObj) is a class method. • It takes an object reference of type PrintStream • It is for redirecting System.out to the given object. • System.setErr(someObj) is a class method. • It takes an object reference of type PrintStream • It is for redirecting System.err to the given object. • System.setIn(someObj) is a class method. • It takes an object reference of type InputStream • It is for redirecting System.in to the given object.

  20. Significance • We can redirect the print out beforeexecutingan existing class/ object/ program like this: import java.io.*; class Redirector { public static void main(String[] args) throws IOException { PrintStream f = new PrintStream("out.txt"); System.setOut(f); TargetClass.main(args); } }

  21. Redirector in Action Redirector main( args ) - Create new PrintStream object [f] - Redirect System.out to [f] - Send message to main() method of TargetClass (pass parameter args as is) TargetClass main( args ) System.out.println("Hello"); would go to [f]

  22. Extras • Under Command Prompt/ Shell, standard input/ output re-direction is also available in command line: • e.g. dir > filelist.txt myprog.exe > output.txt myprog.exe < input.txt myprog.exe < input.txt > output.txt

  23. Soul of Object Oriented Programming • Encapsulation • Protecting Data and Method: Class and Object Access Control • Modularity • Structured Class and Method: Divide-and-Conquer • Inheritance • Extends Mechanism: Reuse-and-Build Related Classes • Polymorphism • Dynamic Type Binding: Type-Oriented Method Invocation

  24. What’re Inherited Exactly? public/protected static/instance fields/methods Octopus OctopusWatch public useValue() addValue() protected value private cardDimension public useValue() addValue() protected value

  25. What’re NOT Inherited? private static/instance fields/methods • Although they are not inherited, we may re-declare them in the subclass. • However, the context is not the same as the superclass.

  26. What’s More? • Modifiers public, private and protectedDO NOT ONLY dictate what would be inherited. • Remember that they ALSO affect the scope of a member.

  27. Privacy • Member (field/method) modifiers revisited: • public: a member is accessible anywhere • private: a member is ONLY accessible by that class • protected: a member is ONLY accessible by that class AND the subclasses of that class.

  28. Protected Member class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; ... } class CurrentAccount extends Account {...} • balance is a protected member of the class Account. • CurrentAccount is a subclass of Account, thus it can inherit and access balance too!

  29. Graphically Octopus OctopusWatch Valid Access public useValue() addValue() protected value private cardDimension public useValue() addValue() protected value timerMethod() time Invalid Access OtherClass someMethod()

  30. Super Construction • Constructors revisited: • On creating a new object, a constructor of the corresponding class will be invoked to initialize the object. • Subclass may have its own constructors. • Shall such constructors be responsible for doing the initialization performed by the constructors of the superclass?

  31. class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } } class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); } // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque(); } } Responsible for initializing the field noChequesIssued Example Responsible for initializing the field balance

  32. class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } } class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); } // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque(); } } On creating a new CurrentAccount object, this constructor will be called Example On creating a new Account object, this constructor will be called

  33. class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } } class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); } // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque(); } } On creating a new CurrentAccount object, this constructor will be called Example Remember that the field balance is inherited in CurrentAccount objects.

  34. class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } } class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); } // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque(); } } On creating a new CurrentAccount object, this constructor will be called Example We thus have to call the constructor of the superclass (Account) to perform suitable initializations

More Related