by Dinesh Thakur Category: Stream

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 in the current directory (java) in the Window OS, use the following statements.

For absolute path,

File file = new File("C:\\java\\");

For relative path,

File file = new File("");

• 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, "");

creates a File object f2 with the filename existing in the directory specified by File object dir.


 class FileCreate
            public static void main(String[] args)
                 File file = new File("");
                 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()));

File Class Methods in Java with Examples

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles