SlideShare a Scribd company logo
1
5.1 Class File
• Class File useful for retrieving information
about files and directories from disk
• Objects of class File do not open files or provide
any file-processing capabilities
2
Creating File Objects
• Class File provides four constructors:
1. Takes String specifying name and path (location of file on
disk)
2. Takes two Strings, first specifying path and second specifying
name of file
3. Takes File object specifying path and String specifying
name of file
4. Takes URI object specifying name and location of file
• Different kinds of paths
– Absolute path – contains all directories, starting with the root
directory, that lead to a specific file or directory
– Relative path – normally starts from the directory in which the
application began executing
3
Fig. 5.1 | File methods.
(Part 1 of 2)
Method Description
boolean canRead() Returns true if a file is readable by the current application; false
otherwise.
boolean canWrite() Returns true if a file is writable by the current application; false
otherwise.
boolean exists() Returns true if the name specified as the argument to the File
constructor is a file or directory in the specified path; false otherwise.
boolean isFile() Returns true if the name specified as the argument to the File
constructor is a file; false otherwise.
boolean isDirectory() Returns true if the name specified as the argument to the File
constructor is a directory; false otherwise.
boolean isAbsolute() Returns true if the arguments specified to the File constructor
indicate an absolute path to a file or directory; false otherwise.
4
Fig.5.1 | File methods.
(Part 2 of 2)
Method Description
String getAbsolutePath() Returns a string with the absolute path of the file or directory.
String getName() Returns a string with the name of the file or directory.
String getPath() Returns a string with the path of the file or directory.
String getParent() Returns a string with the parent directory of the file or directory (i.e.,
the directory in which the file or directory can be found).
long length() Returns the length of the file, in bytes. If the File object represents a
directory, 0 is returned.
long lastModified() Returns a platform-dependent representation of the time at which the
file or directory was last modified. The value returned is useful only for
comparison with other values returned by this method.
String[] list() Returns an array of strings representing the contents of a directory.
Returns null if the File object does not represent a directory.
5
Error-Prevention Tip 5.1
Use File method isFile to determine whether a
File object represents a file (not a directory)
before attempting to open the file.
6
Demonstrating Class File
• Common File methods
– exists – return true if file exists where it is specified
– isFile – returns true if File is a file, not a directory
– isDirectory – returns true if File is a directory
– getPath – return file path as a string
– list – retrieve contents of a directory
• Separator character – used to separate directories and
files in a path
– Windows uses 
– UNIX uses /
– Java process both characters, File.pathSeparator can be
used to obtain the local computer’s proper separator character
7
Outline
FileDemonstration
.java
(1 of 2)
1 // Fig. 5.1: FileDemonstration.java
2 // Demonstrating the File class.
3 import java.io.File;
4
5 public class FileDemonstration
6 {
7 // display information about file user specifies
8 public void analyzePath( String path )
9 {
10 // create File object based on user input
11 File name = new File( path );
12
13 if ( name.exists() ) // if name exists, output information about it
14 {
15 // display file (or directory) information
16 System.out.printf(
17 "%s%sn%sn%sn%sn%s%sn%s%sn%s%sn%s%sn%s%s",
18 name.getName(), " exists",
19 ( name.isFile() ? "is a file" : "is not a file" ),
20 ( name.isDirectory() ? "is a directory" :
21 "is not a directory" ),
22 ( name.isAbsolute() ? "is absolute path" :
23 "is not absolute path" ), "Last modified: ",
24 name.lastModified(), "Length: ", name.length(),
25 "Path: ", name.getPath(), "Absolute path: ",
26 name.getAbsolutePath(), "Parent: ", name.getParent() );
27
Create new File object; user
specifies file name and path
Returns true if file or directory
specified exists
Retrieve name of file or directoryReturns true if name is a
file, not a directoryReturns true if name is a
directory, not a file
Returns true if path was
an absolute path
Retrieve time file or directory
was last modified (system-
dependent value)
Retrieve length of file in bytes
Retrieve path entered as a string
Retrieve absolute path of file or directoryRetrieve parent directory (path
where File object’s file or
directory can be found)
8
Outline
FileDemonstration
.java
(2 of 2)
28 if ( name.isDirectory() ) // output directory listing
29 {
30 String directory[] = name.list();
31 System.out.println( "nnDirectory contents:n" );
32
33 for ( String directoryName : directory )
34 System.out.printf( "%sn", directoryName );
35 } // end else
36 } // end outer if
37 else // not file or directory, output error message
38 {
39 System.out.printf( "%s %s", path, "does not exist." );
40 } // end else
41 } // end method analyzePath
42 } // end class FileDemonstration
Returns true if File is a directory, not a file
Retrieve and display
contents of directory
9
Outline
FileDemonstration
Test.java
(1 of 3)
1 // Fig. 5.2: FileDemonstrationTest.java
2 // Testing the FileDemonstration class.
3 import java.util.Scanner;
4
5 public class FileDemonstrationTest
6 {
7 public static void main( String args[] )
8 {
9 Scanner input = new Scanner( System.in );
10 FileDemonstration application = new FileDemonstration();
11
12 System.out.print( "Enter file or directory name here: " );
13 application.analyzePath( input.nextLine() );
14 } // end main
15 } // end class FileDemonstrationTest
10
Outline
FileDemonstration
Test.java
(2 of 3)
Enter file or directory name here: C:Program FilesJavajdk1.5.0demojfc
jfc exists
is not a file
is a directory
is absolute path
Last modified: 1083938776645
Length: 0
Path: C:Program FilesJavajdk1.5.0demojfc
Absolute path: C:Program FilesJavajdk1.5.0demojfc
Parent: C:Program FilesJavajdk1.5.0demo
Directory contents:
CodePointIM
FileChooserDemo
Font2DTest
Java2D
Metalworks
Notepad
SampleTree
Stylepad
SwingApplet
SwingSet2
TableExample
11
Outline
FileDemonstration
Test.java
(3 of 3)
Enter file or directory name here:
C:Program FilesJavajdk1.5.0demojfcJava2Dreadme.txt
readme.txt exists
is a file
is not a directory
is absolute path
Last modified: 1083938778347
Length: 7501
Path: C:Program FilesJavajdk1.5.0demojfcJava2Dreadme.txt
Absolute path: C:Program FilesJavajdk1.5.0demojfcJava2Dreadme.txt
Parent: C:Program FilesJavajdk1.5.0demojfcJava2D
12
Common Programming Error 5.2
Using  as a directory separator rather than  in a
string literal is a logic error. A single  indicates
that the  followed by the next character
represents an escape sequence. Use  to insert a 
in a string literal.
© 2005 Pearson Education Inc. All rights reserved.
import java.io.*;
class File {
public static void main (String args[]) throws Exception{
java.io.File file=new java.io.File (“file.txt”);
if (file.exists()){
System.out.print(“File exists”);
System.exit(0);//1M
}
//create file
java.io.PrintWriter output=new java.io.PrintWriter(file);
output.print(“hello world”);
}
output.close()
}
}
13

More Related Content

What's hot

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Filter
FilterFilter
Filter
Soujanya V
 
Java and OWL
Java and OWLJava and OWL
Java and OWL
Raji Ghawi
 
FireWatir - Web Application Testing Using Ruby and Firefox
FireWatir - Web Application Testing Using Ruby and FirefoxFireWatir - Web Application Testing Using Ruby and Firefox
FireWatir - Web Application Testing Using Ruby and Firefox
angrez
 
XQuery - a technical overview
XQuery -  a technical overviewXQuery -  a technical overview
XQuery - a technical overview
Loren Cahlander
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
Raji Ghawi
 
ALA Interoperability
ALA InteroperabilityALA Interoperability
ALA Interoperability
spacecowboyian
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Java
JavaJava
Semantic Web
Semantic WebSemantic Web
Semantic Web
amberkhan59
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
Jim Bethancourt
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
Hari Christian
 

What's hot (15)

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Filter
FilterFilter
Filter
 
Savitch ch 06
Savitch ch 06Savitch ch 06
Savitch ch 06
 
Java and OWL
Java and OWLJava and OWL
Java and OWL
 
Java servlet
Java servletJava servlet
Java servlet
 
FireWatir - Web Application Testing Using Ruby and Firefox
FireWatir - Web Application Testing Using Ruby and FirefoxFireWatir - Web Application Testing Using Ruby and Firefox
FireWatir - Web Application Testing Using Ruby and Firefox
 
XQuery - a technical overview
XQuery -  a technical overviewXQuery -  a technical overview
XQuery - a technical overview
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
ALA Interoperability
ALA InteroperabilityALA Interoperability
ALA Interoperability
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Java
JavaJava
Java
 
Semantic Web
Semantic WebSemantic Web
Semantic Web
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
 

Viewers also liked

Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
Khirulnizam Abd Rahman
 
Tips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada templateTips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada template
Khirulnizam Abd Rahman
 
Topik 3 Masyarakat Malaysia dan ICT
Topik 3   Masyarakat Malaysia dan ICTTopik 3   Masyarakat Malaysia dan ICT
Topik 3 Masyarakat Malaysia dan ICT
Khirulnizam Abd Rahman
 
Chapter 6 Java IO File
Chapter 6 Java IO FileChapter 6 Java IO File
Chapter 6 Java IO File
Khirulnizam Abd Rahman
 
Html5 + Bootstrap & Mobirise
Html5 + Bootstrap & MobiriseHtml5 + Bootstrap & Mobirise
Html5 + Bootstrap & Mobirise
Khirulnizam Abd Rahman
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
Khirulnizam Abd Rahman
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
Khirulnizam Abd Rahman
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
Khirulnizam Abd Rahman
 
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan HeartwareTopik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
Khirulnizam Abd Rahman
 
Android app development hybrid approach for beginners - Tools Installations ...
Android app development  hybrid approach for beginners - Tools Installations ...Android app development  hybrid approach for beginners - Tools Installations ...
Android app development hybrid approach for beginners - Tools Installations ...
Khirulnizam Abd Rahman
 
Mobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordovaMobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordova
Khirulnizam Abd Rahman
 
Android app development Hybrid approach for beginners
Android app development  Hybrid approach for beginnersAndroid app development  Hybrid approach for beginners
Android app development Hybrid approach for beginners
Khirulnizam Abd Rahman
 

Viewers also liked (12)

Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
 
Tips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada templateTips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada template
 
Topik 3 Masyarakat Malaysia dan ICT
Topik 3   Masyarakat Malaysia dan ICTTopik 3   Masyarakat Malaysia dan ICT
Topik 3 Masyarakat Malaysia dan ICT
 
Chapter 6 Java IO File
Chapter 6 Java IO FileChapter 6 Java IO File
Chapter 6 Java IO File
 
Html5 + Bootstrap & Mobirise
Html5 + Bootstrap & MobiriseHtml5 + Bootstrap & Mobirise
Html5 + Bootstrap & Mobirise
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan HeartwareTopik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
 
Android app development hybrid approach for beginners - Tools Installations ...
Android app development  hybrid approach for beginners - Tools Installations ...Android app development  hybrid approach for beginners - Tools Installations ...
Android app development hybrid approach for beginners - Tools Installations ...
 
Mobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordovaMobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordova
 
Android app development Hybrid approach for beginners
Android app development  Hybrid approach for beginnersAndroid app development  Hybrid approach for beginners
Android app development Hybrid approach for beginners
 

Similar to Chapter 5 Class File

File Handlingb in java. A brief presentation on file handling
File Handlingb in java. A brief presentation on file handlingFile Handlingb in java. A brief presentation on file handling
File Handlingb in java. A brief presentation on file handling
abdulsamadbrohi461
 
Recursively Searching Files and DirectoriesSummaryBuild a class .pdf
Recursively Searching Files and DirectoriesSummaryBuild a class .pdfRecursively Searching Files and DirectoriesSummaryBuild a class .pdf
Recursively Searching Files and DirectoriesSummaryBuild a class .pdf
mallik3000
 
Csphtp1 17
Csphtp1 17Csphtp1 17
Csphtp1 17
HUST
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
NavneetSheoran3
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
Mahmoud Ouf
 
import required package file import java.io.File; The Filed.pdf
 import required package file import java.io.File; The Filed.pdf import required package file import java.io.File; The Filed.pdf
import required package file import java.io.File; The Filed.pdf
anandinternational01
 
Files
FilesFiles
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
Mahmoud Ouf
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
PRN USM
 
Php files
Php filesPhp files
Php files
kalyani66
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
Rasan Samarasinghe
 
JDBC
JDBCJDBC
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
Martijn Verburg
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 

Similar to Chapter 5 Class File (20)

My History
My HistoryMy History
My History
 
History
HistoryHistory
History
 
File Handlingb in java. A brief presentation on file handling
File Handlingb in java. A brief presentation on file handlingFile Handlingb in java. A brief presentation on file handling
File Handlingb in java. A brief presentation on file handling
 
Recursively Searching Files and DirectoriesSummaryBuild a class .pdf
Recursively Searching Files and DirectoriesSummaryBuild a class .pdfRecursively Searching Files and DirectoriesSummaryBuild a class .pdf
Recursively Searching Files and DirectoriesSummaryBuild a class .pdf
 
Csphtp1 17
Csphtp1 17Csphtp1 17
Csphtp1 17
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
import required package file import java.io.File; The Filed.pdf
 import required package file import java.io.File; The Filed.pdf import required package file import java.io.File; The Filed.pdf
import required package file import java.io.File; The Filed.pdf
 
Files
FilesFiles
Files
 
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Php files
Php filesPhp files
Php files
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
Files nts
Files ntsFiles nts
Files nts
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
 
JDBC
JDBCJDBC
JDBC
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 

More from Khirulnizam Abd Rahman

Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Khirulnizam Abd Rahman
 
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan InsanPanduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Khirulnizam Abd Rahman
 
Topik 1 Islam dan Teknologi Maklumat
Topik 1 Islam dan Teknologi MaklumatTopik 1 Islam dan Teknologi Maklumat
Topik 1 Islam dan Teknologi Maklumat
Khirulnizam Abd Rahman
 
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Khirulnizam Abd Rahman
 
Chapter 1 Nested Control Structures
Chapter 1 Nested Control StructuresChapter 1 Nested Control Structures
Chapter 1 Nested Control Structures
Khirulnizam Abd Rahman
 
Chapter 1 nested control structures
Chapter 1 nested control structuresChapter 1 nested control structures
Chapter 1 nested control structures
Khirulnizam Abd Rahman
 
DTCP2023 Fundamentals of Programming
DTCP2023 Fundamentals of ProgrammingDTCP2023 Fundamentals of Programming
DTCP2023 Fundamentals of Programming
Khirulnizam Abd Rahman
 
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan InsanNpwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Khirulnizam Abd Rahman
 
Simple skeleton of a review paper
Simple skeleton of a review paperSimple skeleton of a review paper
Simple skeleton of a review paper
Khirulnizam Abd Rahman
 
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell   khirulnizamRangka kursus pembangunan aplikasi android kuiscell   khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
Khirulnizam Abd Rahman
 
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copyKhirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copyKhirulnizam Abd Rahman
 
Senarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahanSenarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahan
Khirulnizam Abd Rahman
 
Al mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathuratAl mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathuratKhirulnizam Abd Rahman
 
Android development beginners faq
Android development  beginners faqAndroid development  beginners faq
Android development beginners faq
Khirulnizam Abd Rahman
 
Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam Abd Rahman
 

More from Khirulnizam Abd Rahman (18)

Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
 
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan InsanPanduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
 
Topik 1 Islam dan Teknologi Maklumat
Topik 1 Islam dan Teknologi MaklumatTopik 1 Islam dan Teknologi Maklumat
Topik 1 Islam dan Teknologi Maklumat
 
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
 
Chapter 1 Nested Control Structures
Chapter 1 Nested Control StructuresChapter 1 Nested Control Structures
Chapter 1 Nested Control Structures
 
Chapter 1 nested control structures
Chapter 1 nested control structuresChapter 1 nested control structures
Chapter 1 nested control structures
 
DTCP2023 Fundamentals of Programming
DTCP2023 Fundamentals of ProgrammingDTCP2023 Fundamentals of Programming
DTCP2023 Fundamentals of Programming
 
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan InsanNpwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
 
Simple skeleton of a review paper
Simple skeleton of a review paperSimple skeleton of a review paper
Simple skeleton of a review paper
 
Airs2014 brochure
Airs2014 brochureAirs2014 brochure
Airs2014 brochure
 
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell   khirulnizamRangka kursus pembangunan aplikasi android kuiscell   khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
 
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copyKhirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copy
 
Maklumat program al quran dan borang
Maklumat program al quran dan borangMaklumat program al quran dan borang
Maklumat program al quran dan borang
 
Senarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahanSenarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahan
 
Al mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathuratAl mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathurat
 
Kemalangan akibat tumpuan terganggu
Kemalangan akibat tumpuan tergangguKemalangan akibat tumpuan terganggu
Kemalangan akibat tumpuan terganggu
 
Android development beginners faq
Android development  beginners faqAndroid development  beginners faq
Android development beginners faq
 
Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...
 

Recently uploaded

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 

Recently uploaded (20)

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 

Chapter 5 Class File

  • 1. 1 5.1 Class File • Class File useful for retrieving information about files and directories from disk • Objects of class File do not open files or provide any file-processing capabilities
  • 2. 2 Creating File Objects • Class File provides four constructors: 1. Takes String specifying name and path (location of file on disk) 2. Takes two Strings, first specifying path and second specifying name of file 3. Takes File object specifying path and String specifying name of file 4. Takes URI object specifying name and location of file • Different kinds of paths – Absolute path – contains all directories, starting with the root directory, that lead to a specific file or directory – Relative path – normally starts from the directory in which the application began executing
  • 3. 3 Fig. 5.1 | File methods. (Part 1 of 2) Method Description boolean canRead() Returns true if a file is readable by the current application; false otherwise. boolean canWrite() Returns true if a file is writable by the current application; false otherwise. boolean exists() Returns true if the name specified as the argument to the File constructor is a file or directory in the specified path; false otherwise. boolean isFile() Returns true if the name specified as the argument to the File constructor is a file; false otherwise. boolean isDirectory() Returns true if the name specified as the argument to the File constructor is a directory; false otherwise. boolean isAbsolute() Returns true if the arguments specified to the File constructor indicate an absolute path to a file or directory; false otherwise.
  • 4. 4 Fig.5.1 | File methods. (Part 2 of 2) Method Description String getAbsolutePath() Returns a string with the absolute path of the file or directory. String getName() Returns a string with the name of the file or directory. String getPath() Returns a string with the path of the file or directory. String getParent() Returns a string with the parent directory of the file or directory (i.e., the directory in which the file or directory can be found). long length() Returns the length of the file, in bytes. If the File object represents a directory, 0 is returned. long lastModified() Returns a platform-dependent representation of the time at which the file or directory was last modified. The value returned is useful only for comparison with other values returned by this method. String[] list() Returns an array of strings representing the contents of a directory. Returns null if the File object does not represent a directory.
  • 5. 5 Error-Prevention Tip 5.1 Use File method isFile to determine whether a File object represents a file (not a directory) before attempting to open the file.
  • 6. 6 Demonstrating Class File • Common File methods – exists – return true if file exists where it is specified – isFile – returns true if File is a file, not a directory – isDirectory – returns true if File is a directory – getPath – return file path as a string – list – retrieve contents of a directory • Separator character – used to separate directories and files in a path – Windows uses – UNIX uses / – Java process both characters, File.pathSeparator can be used to obtain the local computer’s proper separator character
  • 7. 7 Outline FileDemonstration .java (1 of 2) 1 // Fig. 5.1: FileDemonstration.java 2 // Demonstrating the File class. 3 import java.io.File; 4 5 public class FileDemonstration 6 { 7 // display information about file user specifies 8 public void analyzePath( String path ) 9 { 10 // create File object based on user input 11 File name = new File( path ); 12 13 if ( name.exists() ) // if name exists, output information about it 14 { 15 // display file (or directory) information 16 System.out.printf( 17 "%s%sn%sn%sn%sn%s%sn%s%sn%s%sn%s%sn%s%s", 18 name.getName(), " exists", 19 ( name.isFile() ? "is a file" : "is not a file" ), 20 ( name.isDirectory() ? "is a directory" : 21 "is not a directory" ), 22 ( name.isAbsolute() ? "is absolute path" : 23 "is not absolute path" ), "Last modified: ", 24 name.lastModified(), "Length: ", name.length(), 25 "Path: ", name.getPath(), "Absolute path: ", 26 name.getAbsolutePath(), "Parent: ", name.getParent() ); 27 Create new File object; user specifies file name and path Returns true if file or directory specified exists Retrieve name of file or directoryReturns true if name is a file, not a directoryReturns true if name is a directory, not a file Returns true if path was an absolute path Retrieve time file or directory was last modified (system- dependent value) Retrieve length of file in bytes Retrieve path entered as a string Retrieve absolute path of file or directoryRetrieve parent directory (path where File object’s file or directory can be found)
  • 8. 8 Outline FileDemonstration .java (2 of 2) 28 if ( name.isDirectory() ) // output directory listing 29 { 30 String directory[] = name.list(); 31 System.out.println( "nnDirectory contents:n" ); 32 33 for ( String directoryName : directory ) 34 System.out.printf( "%sn", directoryName ); 35 } // end else 36 } // end outer if 37 else // not file or directory, output error message 38 { 39 System.out.printf( "%s %s", path, "does not exist." ); 40 } // end else 41 } // end method analyzePath 42 } // end class FileDemonstration Returns true if File is a directory, not a file Retrieve and display contents of directory
  • 9. 9 Outline FileDemonstration Test.java (1 of 3) 1 // Fig. 5.2: FileDemonstrationTest.java 2 // Testing the FileDemonstration class. 3 import java.util.Scanner; 4 5 public class FileDemonstrationTest 6 { 7 public static void main( String args[] ) 8 { 9 Scanner input = new Scanner( System.in ); 10 FileDemonstration application = new FileDemonstration(); 11 12 System.out.print( "Enter file or directory name here: " ); 13 application.analyzePath( input.nextLine() ); 14 } // end main 15 } // end class FileDemonstrationTest
  • 10. 10 Outline FileDemonstration Test.java (2 of 3) Enter file or directory name here: C:Program FilesJavajdk1.5.0demojfc jfc exists is not a file is a directory is absolute path Last modified: 1083938776645 Length: 0 Path: C:Program FilesJavajdk1.5.0demojfc Absolute path: C:Program FilesJavajdk1.5.0demojfc Parent: C:Program FilesJavajdk1.5.0demo Directory contents: CodePointIM FileChooserDemo Font2DTest Java2D Metalworks Notepad SampleTree Stylepad SwingApplet SwingSet2 TableExample
  • 11. 11 Outline FileDemonstration Test.java (3 of 3) Enter file or directory name here: C:Program FilesJavajdk1.5.0demojfcJava2Dreadme.txt readme.txt exists is a file is not a directory is absolute path Last modified: 1083938778347 Length: 7501 Path: C:Program FilesJavajdk1.5.0demojfcJava2Dreadme.txt Absolute path: C:Program FilesJavajdk1.5.0demojfcJava2Dreadme.txt Parent: C:Program FilesJavajdk1.5.0demojfcJava2D
  • 12. 12 Common Programming Error 5.2 Using as a directory separator rather than in a string literal is a logic error. A single indicates that the followed by the next character represents an escape sequence. Use to insert a in a string literal.
  • 13. © 2005 Pearson Education Inc. All rights reserved. import java.io.*; class File { public static void main (String args[]) throws Exception{ java.io.File file=new java.io.File (“file.txt”); if (file.exists()){ System.out.print(“File exists”); System.exit(0);//1M } //create file java.io.PrintWriter output=new java.io.PrintWriter(file); output.print(“hello world”); } output.close() } } 13