File
Java file class is an abstract representation of directory pathnames and file pathnames.
Syntax for declaring java.io.File class is as follows:
public class File extends Object implements Serializable, Comparable
For a given java file, the pathname might be relative or absolute. There are various methods in a file class to work with directories and files, including creating a newer file or directory, deletion and renaming any file or directory, listing data and contents of a directory, etc.
Different formats are available for directory names and file names; therefore, only a string is not adequate for naming them.
Here are some more things to know about the Java file class:
- A pathname in a string form or abstract can be relative or absolute. You can get the parent of an abstract pathname by invoking the class method called getParent().
- First, it is essential to create the File class object by passing the directory name or the filename. Further, a file system might implement a few restrictions to operations on the actual object of the file system, like writing, reading, and executing. All these restrictions are termed access permissions.
- File class instances are immutable, and therefore, after being created, the abstract pathname of the file object cannot be altered.
Constructors of Java File class:
- File (File parent, String child): It creates a new file instance using the parent abstract pathname and the pathname string of the child class.
- File (String pathname): It creates a new file instance after it converts the provided pathname string into an abstract pathname.
- File (String parent, String child): It creates a new file instance using the pathname string of parent and the child classes.
- File (URL uri): It create a new file instance after it converts the file URL into an abstract pathname.
Example :
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
try {
File file = new File("knowledge2life.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT: