In order in create File object, the File class provides the following constructors.
• File (String pathname): Creates a File object associated with the file or directory specified by pathname. The pathname can contain path information as well as a file or directory name.
To create an object for the file named HelloJavaExample.java in the current directory (java) in the Window OS, use the following statements.
For absolute path,
File file = new File(“C:\\java\\ HelloJavaExample.java”);
For relative path,
File file = new File(“HelloJavaExample.java”);
• File (File dir, String name) Creates a File object with the given file or directory name in the directory specified by the dir parameter of type File. If the dir parameter is null, this constructor then creates a File object using the current directory. For example, the statement
File dir = new File(“C:/java/classes”);
File f2 = new File(dir, ” HelloJavaExample.java”);
creates a File object f2 with the filename HelloJavaExample.java existing in the directory specified by File object dir.
import java.io.*;
class FileCreate
{
public static void main(String[] args)
{
File file = new File("HelloJavaExample.java");
System.out.println("File Exists : "+file.exists());
System.out.println("Length of File is : "+file.length());
System.out.println("Can Read File : "+file.canRead());
System.out.println("Can Write to File : "+file.canWrite());
System.out.println("whether File is a Directory : "+file.isDirectory());
System.out.println("whether File is a File : "+file.isFile());
System.out.println("File name is : "+file.getName());
System.out.println("File absolute path is : "+file.getAbsolutePath());
System.out.println("File path is : "+file.getPath());
System.out.println("File parent directory is : "+file.getParent());
System.out.println("File last modified on : "+ new java.util.Date(file.lastModified()));
}
}