This
class is used to represent files and directory paths (but not data of the file,
file data is represented by FileInputStream and FileOutputStream). Basically,
this class is used to create, delete, rename files and also used to know about
the files and directories like, given file name represents file or directory,
type of the file is read-only or writable, last modified etc.
Instances
of the file class are immutable that is once created, the abstract pathname
represented by a file object will never change, because we do not have setter
method to change the file name in this file object. But we have getter method
to get file name.
Constructors of File class
1. File f = new File(String s) – Creates
a java file object to represent name of the file or directory.
2. File f = new File(String subdir, String
name) – To create a java file object to represent name of the file
or directory, in specified subdirectory.
Methods of File class
1. boolean exists() – Returns
true if the specified file or directory is available.
2. boolean createNewFile() – This method
first checks whether the physical file is already available or not. If it is
already available then this method returns false without creating new file. If
it isn’t available then this method creates a new file and returns true.
3. boolean mkdir() – Creates
new sub directory with given file name.
4. boolean isFile() – Return
true if the underlying file object represents a physical file.
5. boolean isDirectory() – This method
checks if subdirectory is available, if so it returns true otherwise false.
6. String[] list() – To list
out the names of all files and subdirectories present in the specified
directory.
7. long length() – Returns
the number of characters present in the file.
8. boolean delete() – To delete
the specified file or directory.
Example –
import
java.io.File;
import
java.io.IOException;
public class
File1 {
public static void
main(String[] args) throws IOException {
File f = new
File("abc.txt");
File f1 = new
File("xyz");
int count=0;
boolean a = f.exists(); //
already exists so true
System.out.println(a);
boolean b = f.createNewFile(); //
cannot create so false
System.out.println(b);
boolean c = f1.mkdir(); //
created directory xyz inside Project folder
System.out.println(c);
boolean d = f1.isDirectory();
System.out.println(d); //
directory available so true
String [] e = f1.list(); //
total files in a directory
for(String
g : e){
count++;
System.out.println(g);
}
System.out.println("The total number of files are = "+count);
boolean h = f1.delete(); // deleted xyz directory
System.out.println(h);
}
}
Output –
true
false
false
true
The total number of files are = 0
true
No comments:
Post a Comment