Java File Structure File class which is defined

  • Slides: 24
Download presentation
Java File Structure

Java File Structure

§ File class which is defined by java. io does not operate on streams

§ File class which is defined by java. io does not operate on streams vdeals directly with files and the file system v. File class describes the properties of a file v it does not specify how information is retrieved from or stored in files. v. File object is used to obtain the information, associated with a disk file, such as permission, time , data, and directory path v. There are three constructor methods in java. io. File. v. Each takes some variation of a filename as an argument(s).

File Constructors

File Constructors

v The simplest is File constructor is: public File(String directory. Path) vdirectorypath is simply

v The simplest is File constructor is: public File(String directory. Path) vdirectorypath is simply a String with either a full or relative pathname to the file which can be understood by the host operating system. File f 1 = new File ("25. html"); File f 2 = new File ("/etc/passwd"); v We can separate the path and the filename using the following constructor: public File (String directory. Path, String filename) File f 2 = new File ("/etc", "passwd"); v The third constructor is: public File (File dir. Obj, String filename) v. File object itself instead of a String. File f 3= new File (f 1, “passwd”)

File Methods

File Methods

public String get. Name() v. The most basic question which is asked a file

public String get. Name() v. The most basic question which is asked a file is "What is your name? " v This is done with the get. Name() method which takes no arguments and returns a String. v. The String returned is just the name of the file. v. It does not include any piece of the directory or directories that contain this file. v. In other words we get back "file 1" instead of "/java/users/file 1".

public String get. Path() v get. Path() returns a String that contains the path

public String get. Path() v get. Path() returns a String that contains the path being used for this File. v It will be relative or absolute depending on how the File object was created. public String get. Absolute. Path() v get. Absolute. Path() returns the complete, non-relative path to the file. public String get. Canonical. Path() throws IOException v get. Canonical. Path() returns the canonical form of this File object's pathname. This is system-dependent. public String get. Parent() v get. Parent() returns a String that contains the name of the single directory which contains this file in the hierarchy. v It does not return a full path all the way back up to the root. If the file is at the top level of the disk then it has no parent directory and null is returned.

public boolean exists() throws Security Exception v The exists() method indicates whether or not

public boolean exists() throws Security Exception v The exists() method indicates whether or not a particular file exists where you expect it to be. public boolean can. Write() throws Security. Exception v The can. Write() method indicates whether you have write access to this file. It's not a bad idea to check can. Write() before trying to put data in a file. public boolean can. Read() throws Security. Exception v The can. Read() method indicates whether we have read access to this file. It a good idea to check can. Read() before trying to read data out of a file.

public boolean is. File() throws Security. Exception v The is. File() method indicates whether

public boolean is. File() throws Security. Exception v The is. File() method indicates whether this is file exists and is a normal file, in other words not a directory. public boolean is. Directory() throws Security. Exception v The is. Directory() returns true if this file exists and is a directory. public boolean is. Absolute() v is. Absolute() returns true if the file name is an absolute path and false if it's a relative path. public long last. Modified() throws Security. Exception v last. Modified() returns the last modification time. Since the conversion between this long and a real date is platform dependent, you should only use this to compare modification dates of different files.

public boolean rename. To(File destination) throws Security. Exception v f 1. rename. To(f 2)

public boolean rename. To(File destination) throws Security. Exception v f 1. rename. To(f 2) tries to change the name of f 1 to f 2. v This may involve a move to a different directory if the filenames so indicate. v If f 2 already exists, then it is overwritten by f 1 (permissions permitting). v If f 1 is renamed, the method returns true. Otherwise it returns false. pubic String[] list() throws Security. Exception v The list() method returns an array of Strings initialized to the names of each file in directory f v It's useful for processing all the files in a directory.

Security. Exception class java. lang Class Security. Exception java. lang. Object java. lang. Throwable

Security. Exception class java. lang Class Security. Exception java. lang. Object java. lang. Throwable java. lang. Exception java. lang. Runtime. Exception java. lang. Security. Exception

public long length() throws Security. Exception v f. length() is the length of the

public long length() throws Security. Exception v f. length() is the length of the file in bytes. public boolean mkdir() v f. mkdir() tries to create a directory with the given name. v If the directory is created, the method returns true. v Otherwise it returns false. public boolean delete() throws Security. Exception v f. delete() tries to delete the file f. v This method returns true if the file existed and was deleted. (You can't delete a file that doesn't exist). v Otherwise it returns false. v The File class also contains the usual equals(), hash. Code() and to. String() methods which behave exactly as you would expect. It does not contain a clone() method.

Complete The Following Java Program v. There are many methods that allow us to

Complete The Following Java Program v. There are many methods that allow us to examine the properties of a simple file object. v. The following Java program output demonstrates several File methods application v. Write Java code according to that program output

File Name: COPYRIGHT Path: /java/COPYRIGHT Parent: /java exists is writeable is readable is not

File Name: COPYRIGHT Path: /java/COPYRIGHT Parent: /java exists is writeable is readable is not a directory is normal file is absolute File last modified: 812465204000 File size: 695 Bytes

import java. io. File class File. Demo { static void p (String s) {

import java. io. File class File. Demo { static void p (String s) { System. out. println (s); } public static void main (String args[ ]) { File f 1= new File (“/java/COPYRIGHT”); …………… p (“Parent: “ +f 1. get. Parent()); …………………. . p(f 1. can. Write() ? ”is writeable” : “is not writeable”); ………………… p (f 1. is. Absolute() ? “is absolute” : “is not absolute”); …………………. } }

The ? Operator v The ? operator is a special ternary (three-way) operator that

The ? Operator v The ? operator is a special ternary (three-way) operator that can replace certain types of if-thenelse statements expression 1 ? Expression 2 : expression 3 v expression 1 can be any expression that evaluates to a boolean value. v If expression 1 is true, then expression 2 is evaluated; otherwise expression 3 is evaluated. v The result of ? operation is that of the expression evaluated. v Both expression 2 and expression 3 are required to return the same type, which can not be void

ratio = denom == 0 ? 0 : num /denom; v If denom equals

ratio = denom == 0 ? 0 : num /denom; v If denom equals zero, then expression between the question mark and colon is evaluated and used as the value of the entire ? expression v If denom is not equal zero, then the expression after the colon is evaluated and used for the value of the entire ? expression. v The result produces by the ? operator is assigned to ratio.

Exercise Write the Java code by using the ? operator for the following program

Exercise Write the Java code by using the ? operator for the following program output: Absolute value of 20 is 20 Absolute value of -10 is 10 Hint: assign the values 20 and -10 before writing the ? operator.

Try and catch example (The homework on 5 December) import java. util. Random; class

Try and catch example (The homework on 5 December) import java. util. Random; class A { public static void main (String args[ ]) { int a=0, b=0, c=0; Random r = new Random(); for ( int i=0; i<320; i++ { try { b= r. next. Int(); c=r. next. Int(); a=12345 / ( b/c); } catch (Arithmetic. Exception e) { System. out. println (“Division by zero. ”); a=0; //set a zero and continue } System. out. println ( “a: “ +a); } } }

Explaining the Different Java Codes with Object Oriented Properties A Payroll System Using Polymorphism

Explaining the Different Java Codes with Object Oriented Properties A Payroll System Using Polymorphism

public abstract class Employee { //abstract class cannot be instantiated private String first. Name;

public abstract class Employee { //abstract class cannot be instantiated private String first. Name; //abstract class can have instance data and nonabstract methods for subclasses private String last. Name; // constructor public Employee( String first, String last ) { // abstract class can have constructors for subclasses to initialize inherited data first. Name = first; last. Name = last; } public String get. First. Name() { // get first name //abstract class can have instance data and nonabstract methods for subclasses return first. Name; public String get. Last. Name() } { // get last name //abstract class can have instance data and nonabstract methods for subclasses return last. Name; public String to. String() } { //abstract class can have instance data and nonabstract methods for subclasses return first. Name + ' ' + last. Name; }

// Boss class derived from Employee. public final class Boss extends Employee { /*Boss

// Boss class derived from Employee. public final class Boss extends Employee { /*Boss is an Employee subclass and Boss inherits Employee’s public methods except for constuctor*/ private double weekly. Salary; public Boss( String first, String last, double salary ) // constructor for class Boss super( first, last ); // call superclass constructor // Explicit call to Employee constructor using super set. Weekly. Salary( salary ); } public void set. Weekly. Salary( double salary ) // set Boss's salary { weekly. Salary = ( salary > 0 ? salary : 0 ); } public double earnings() { // get Boss's pay //Required to implement Employee’s method earnings (polymorphism return weekly. Salary; } public String to. String() { // get String representation of Boss's name return "Boss: " + super. to. String(); } } // end class Boss

// Commission. Worker class derived from Employee public final class Commission. Worker extends Employee

// Commission. Worker class derived from Employee public final class Commission. Worker extends Employee { //Commission. Worker is an Employee subclass private double salary; // base salary per week private double commission; // amount per item sold private int quantity; // total items sold for week // constructor for class Commission. Worker public Commission. Worker (String first, String last, double salary, double commission, int quantity ) { super( first, last ); // call superclass constructor //Explicit call to Employee constructor using super set. Salary( salary ); set. Commission( commission ); set. Quantity( quantity ); } // set Commission. Worker's weekly base salary public void set. Salary( double weekly. Salary ) { salary = ( weekly. Salary > 0 ? weekly. Salary : 0 ); } // set Commission. Worker's commission public void set. Commission( double item. Commission ) { commission = ( item. Commission > 0 ? item. Commission : 0 ); }

/*Subclasses must implement abstract method. Abstract method that must be implemented for each derived

/*Subclasses must implement abstract method. Abstract method that must be implemented for each derived class of Employee from which objects are instantiated . */ public abstract double earnings() ; //Subclasses must implement abstract method } // end class Employee. . . . . . . . . . The codes will continue about this problem