Transcript File
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 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).
File Constructors
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”)
File Methods
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" .
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.
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.
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.
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.
SecurityException
class
java.lang
Class SecurityException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.SecurityException
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.
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
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 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”);
…………………………………….
} }
The ? Operator
The ? operator is a special ternary (three-way)
operator that can replace certain types of if-thenelse statements
expression1 ? Expression2 : expression3
expression1 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
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.
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 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);
}
}
}
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 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 subclasses
return lastName;
public String toString()
}
{
//abstract class can have instance data and nonabstract methods for subclasses
return firstName + ' ' + lastName;
}
// 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 name
return "Boss: " + super.toString();
}
} // end class Boss
// 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
super( first, last ); // call superclass constructor
//Explicit call to
setSalary( salary );
}
// set CommissionWorker's weekly base salary
p
u
b
l
i
c
v
o
i
d
Employee constructor using
s
u
p
e
r
/*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 implementab stra c t method
}
// end class Employee
...............................
................................
................................
................................
.................................
The codes will continue about this problem