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.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
Advertisements

Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
CS102--Object Oriented Programming Lecture 8: – More about Inheritance When to use inheritance Relationship between classes Rules to follow Copyright ©
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Chapter 10: Inheritance and Polymorphism
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
CS 240 Week 3. List’Em java Grep [-r] directoryName fileSelectionPattern substringSelectionPattern Run Demo java LineCount [-r] directoryName fileSelectionPattern.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
Interfaces Need arising from software engineering –Disparate groups of programmers need to agree to a “contract” that spells out how their software interacts.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
CMSC 202 Inheritance II. Version 10/102 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
MIT AITI 2004 – Lecture 12 Inheritance. What is Inheritance?  In the real world: We inherit traits from our mother and father. We also inherit traits.
1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
O O P Polymorphism Object Oriented Programming Prepared & Presented by: dr.Ismail Farahat Chapter 4.
Object Oriented Programming
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Interfaces and Inner Classes
1 Advanced Programming Inheritance (2). 2 Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
תוכנה 1 תרגול מס ' 4 שימוש במחלקות קיימות : קלט / פלט (IO)
Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
The Object class Object package java.lang Object clone equals hashCode toString aCopy toThis hash string ! yesOrNo.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
BY:- TOPS Technologies
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Java IO Exploring the java.io package and living to talk about it.
Fundamental of Java Programming
Sequential files creation & writing
IO in java.
Object-oriented Programming in Java
03/10/14 Inheritance-2.
Chapter 5 Hierarchies IS-A associations superclasses subclasses
Programming in Java Files and I/O Streams
Abstract Classes.
Inheritance 2nd Lecture
File class File myFile=new File(“c:/javaDemo/aa
null, true, and false are also reserved.
Chapter 9 Object-Oriented Programming: Inheritance
Extending Classes.
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Inheritance 2nd Lecture
Inheritance.
18 File i/o, Parsing.
Inheritance 2nd Lecture
CMSC 202 Inheritance II.
CS 240 – Advanced Programming Concepts
Presentation transcript:

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: 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-then- else 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 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 ); }

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