24
Java File Structure

Java File Structure. File class which is defined by java.io does not operate on streams deals directly with files and the file system File class

Embed Size (px)

Citation preview

Page 1: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

Java File Structure

Page 2: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

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

deals directly with files and the file system

File class describes the properties of a file it does not specify how information is retrieved from or

stored in files.

File object is used to obtain the information, associated with a disk file, such as permission, time ,data, and directory path

There are three constructor methods in java.io.File.

Each takes some variation of a filename as an argument(s).

Page 3: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

File Constructors

Page 4: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

The simplest is File constructor is:

public File(String directoryPath)directorypath is simply a String with either a full or relative pathname

to the file which can be understood by the host operating system.

File f1 = new File ("25.html");

File f2 = new File ("/etc/passwd");We can separate the path and the filename using the

following constructor:

public File (String directoryPath, String filename)

File f2 = new File ("/etc", "passwd");The third constructor is:

public File (File dirObj, String filename)File object itself instead of a String.

File f3= new File (f1, “passwd”)

Page 5: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

File Methods

Page 6: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

public String getName()

The most basic question which is asked a file is "What is your name?"

This is done with the getName() method which takes no arguments and returns a String.

The String returned is just the name of the file. It does not include any piece of the directory or

directories that contain this file.In other words we get back "file1" instead of

"/java/users/file1" .

Page 7: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

public String getPath() getPath() returns a String that contains the path being used for

this File. It will be relative or absolute depending on how the File object

was created.

public String getAbsolutePath() getAbsolutePath() returns the complete, non-relative path to the

file.

public String getCanonicalPath() throws IOException getCanonicalPath() returns the canonical form of this File

object's pathname. This is system-dependent.

public String getParent() getParent() returns a String that contains the name of the single directory

which contains this file in the hierarchy. 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.

Page 8: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

public boolean exists() throws Security Exception The exists() method indicates whether or not a particular file

exists where you expect it to be.

public boolean canWrite() throws SecurityException The canWrite() method indicates whether you have write

access to this file. It's not a bad idea to check canWrite() before trying to put data in a file.

public boolean canRead() throws SecurityException The canRead() method indicates whether we have read

access to this file. It a good idea to check canRead() before trying to read data out of a file.

Page 9: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

public boolean isFile() throws SecurityException The isFile() method indicates whether this is file exists and is

a normal file, in other words not a directory.

public boolean isDirectory() throws SecurityException The isDirectory() returns true if this file exists and is a

directory.

public boolean isAbsolute() isAbsolute() returns true if the file name is an absolute path

and false if it's a relative path.

public long lastModified() throws SecurityException lastModified() 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.

Page 10: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

public boolean renameTo(File destination) throws

SecurityException

f1.renameTo(f2) tries to change the name of f1 to f2. This may involve a move to a different directory if the filenames

so indicate. If f2 already exists, then it is overwritten by f1 (permissions

permitting). If f1 is renamed, the method returns true. Otherwise it returns

false.

pubic String[] list() throws SecurityException

The list() method returns an array of Strings initialized to the names of each file in directory f

It's useful for processing all the files in a directory.

Page 11: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

SecurityExceptionclass

java.lang Class SecurityException

java.lang.Object

java.lang.Throwable

java.lang.Exception

java.lang.RuntimeException java.lang.SecurityException

Page 12: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

public long length() throws SecurityException f.length() is the length of the file in bytes.

public boolean mkdir() f.mkdir() tries to create a directory with the given name. If the directory is created, the method returns true. Otherwise it returns false.

public boolean delete() throws SecurityException f.delete() tries to delete the file f. This method returns true if the file existed and was deleted.

(You can't delete a file that doesn't exist). Otherwise it returns false.

The File class also contains the usual equals(), hashCode() and toString() methods which behave exactly as you would expect. It does not contain a clone() method.

Page 13: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

Complete The Following Java Program

There are many methods that allow us to examine the properties of a simple file object.

The following Java program output demonstrates several File methods application

Write Java code according to that program output

Page 14: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

File Name: COPYRIGHTPath: /java/COPYRIGHTParent: /javaexistsis writeableis readableis not a directoryis normal fileis absoluteFile last modified:812465204000File size: 695 Bytes

Page 15: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

import java.io.File class FileDemo { static void p (String s) { System.out.println (s); }public static void main (String args[ ]) { File f1= new File (“/java/COPYRIGHT”); ………………………… p (“Parent: “ +f1.getParent()); ………………………………….. p(f1.canWrite() ? ”is writeable” : “is not writeable”); …………………………………… p (f1.isAbsolute() ? “is absolute” : “is not absolute”); ……………………………………. } }

Page 16: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

The ? OperatorThe ? operator is a special ternary (three-way)

operator that can replace certain types of if-then-else statements

expression1 ? Expression2 : expression3expression1 can be any expression that evaluates

to a boolean value.If expression1 is true, then expression2 is

evaluated; otherwise expression3 is evaluated.The result of ? operation is that of the expression

evaluated.Both expression2 and expression3 are required to

return the same type, which can not be void

Page 17: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

ratio = denom == 0 ? 0 : num /denom;

If denom equals zero, then expression between the question mark and colon is evaluated and used as the value of the entire ? expression

If denom is not equal zero, then the expression after the colon is evaluated and used for the value of the entire ? expression.

The result produces by the ? operator is assigned to ratio.

Page 18: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

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.

Page 19: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File 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.nextInt(); c=r.nextInt(); a=12345 / ( b/c); } catch (ArithmeticException e) { System.out.println (“Division by zero.”); a=0; //set a zero and continue } System.out.println ( “a: “ +a); } } }

Page 20: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

Explaining the Different Java Codes with Object Oriented Properties

A Payroll System Using Polymorphism

Page 21: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

public abstract class Employee { //abstract class cannot be instantiated private String firstName; //abstract class can have instance data and nonabstract methods for subclasses private String lastName; // constructor

public Employee( String first, String last ) {// abstract class can have constructors for subclasses to initialize inherited

data firstName = first; lastName = last; }

public String getFirstName() { // get first name//abstract class can have instance data and nonabstract methods for subclasses return firstName; }

public String getLastName() { // get last name //abstract class can have instance data and nonabstract methods for subclassesreturn lastName; }

public String toString() { //abstract class can have instance data and nonabstract methods for subclasses return firstName + ' ' + lastName; }

Page 22: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

// 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 weeklySalary; 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 setWeeklySalary( salary ); } public void setWeeklySalary( double salary ) // set Boss's salary { weeklySalary = ( salary > 0 ? salary : 0 ); }

public double earnings() { // get Boss's pay //Required to implement Employee’s method earnings (polymorphism

return weeklySalary; }

public String toString() { // get String representation of Boss's namereturn "Boss: " + super.toString(); }

} // end class Boss

Page 23: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

// CommissionWorker class derived from Employee public final class CommissionWorker extends Employee {//CommissionWorker 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 CommissionWorker public CommissionWorker (String first, String last, double salary, double commission, int quantity ) { super( first, last ); // call superclass constructor

//Explicit call to Employee constructor using super setSalary( salary ); setCommission( commission ); setQuantity( quantity ); } // set CommissionWorker's weekly base salary public void setSalary( double weeklySalary ) { salary = ( weeklySalary > 0 ? weeklySalary : 0 ); }

// set CommissionWorker's commission public void setCommission( double itemCommission ) { commission = ( itemCommission > 0 ? itemCommission : 0 ); }

Page 24: Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class

/*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