Presentation is loading. Please wait.

Presentation is loading. Please wait.

File and Stream I/O, Redirection Privacy and Super

Similar presentations


Presentation on theme: "File and Stream I/O, Redirection Privacy and Super"— Presentation transcript:

1 File and Stream I/O, Redirection Privacy and Super
Copyright by Michael P.F. Fung

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 Copyright by Michael P.F. Fung

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; ... } Copyright by Michael P.F. Fung

4 The Picture System.out.print()
PrintStream print( ) println( ) PrintStream print( ) println( ) X out in System.out is a PrintStream object reference. We then send a print() message to this object. InputStream InputStream Copyright by Michael P.F. Fung

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 Copyright by Michael P.F. Fung

6 Class PrintStream import java.io.*; ...main(...) throws IOException {
PrintStream myNewFile; 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 } Copyright by Michael P.F. Fung

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 Copyright by Michael P.F. Fung

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 Copyright by Michael P.F. Fung

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(); } Copyright by Michael P.F. Fung

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. Copyright by Michael P.F. Fung

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); } Copyright by Michael P.F. Fung

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. Copyright by Michael P.F. Fung

13 Class Scanner The source could be the keyboard object a file 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(“ ) ); Copyright by Michael P.F. Fung

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 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. Copyright by Michael P.F. Fung

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. Copyright by Michael P.F. Fung

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! } Copyright by Michael P.F. Fung

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

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

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 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. Copyright by Michael P.F. Fung

20 Significance We can redirect the print out before executing an 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); } Copyright by Michael P.F. Fung

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] Copyright by Michael P.F. Fung

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 Copyright by Michael P.F. Fung

23 Extras Under Unix To send program output to "black-hole":
dd: data duplicate command parameter if: infile parameter of: outfile Under Unix To send program output to "black-hole": myprog > /dev/null To get "infinite" zero input: myprog < /dev/zero e.g. erase a harddisk (use with care!) dd if=/dev/zero of=/dev/hda entities are commonly represented as files "null device" /dev/null is a file "zero device" /dev/zero is a file "hard-disk a" /dev/hda is also a file Copyright by Michael P.F. Fung

24 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 Copyright by Michael P.F. Fung

25 What’re Inherited Exactly?
public/protected static/instance fields/methods Octopus OctopusWatch public useValue() addValue() protected value private cardDimension public useValue() addValue() protected value Copyright by Michael P.F. Fung

26 private static/instance fields/methods
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. Copyright by Michael P.F. Fung

27 What’s More? Modifiers public, private and protected DO NOT ONLY dictate what would be inherited. Remember that they ALSO affect the scope of a member. Copyright by Michael P.F. Fung

28 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. Copyright by Michael P.F. Fung

29 Protected Member balance is a protected member of the class Account.
// class field public static double minBalance = ; // 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! Copyright by Michael P.F. Fung

30 Graphically Valid Access Invalid Access Octopus OctopusWatch public
useValue() addValue() protected value private cardDimension public useValue() addValue() protected value timerMethod() time Invalid Access OtherClass someMethod() Copyright by Michael P.F. Fung

31 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? Copyright by Michael P.F. Fung

32 Example Responsible for initializing the field noChequesIssued
class Account { // class field public static double minBalance = ; // 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 balance Copyright by Michael P.F. Fung

33 On creating a new Account object, this constructor will be called
On creating a new CurrentAccount object, this constructor will be called Example class Account { // class field public static double minBalance = ; // 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 Account object, this constructor will be called Copyright by Michael P.F. Fung

34 On creating a new CurrentAccount object, this constructor will be called
Example class Account { // class field public static double minBalance = ; // 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(); Remember that the field balance is inherited in CurrentAccount objects. Copyright by Michael P.F. Fung

35 On creating a new CurrentAccount object, this constructor will be called
Example class Account { // class field public static double minBalance = ; // 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(); We thus have to call the constructor of the superclass (Account) to perform suitable initializations Copyright by Michael P.F. Fung


Download ppt "File and Stream I/O, Redirection Privacy and Super"

Similar presentations


Ads by Google