You are here: Home / Topics / Program to use File class and its methods in Java

Program to use File class and its methods in Java

Filed under: Java on 2023-10-25 06:51:37

//  Program to use File class and its methods

import java.io.*;

class FileDemo
{
   public static void main(String args[ ]) 
   {
       File f = new File("FileDemo.java");

       System.out.println("File : " + f.getName() + (f.isFile() ? " is a file" : " is not a file"));
       System.out.println("Size : " + f.length());
       System.out.println("Path : " + f.getPath());
       System.out.println("Absolute Path : " + f.getAbsolutePath());
       System.out.println("File was last modified : " + f.lastModified());
       System.out.println(f.exists() ? "File exists" : "File does not exist");
       System.out.println(f.canRead() ? "File can be read from" : "File cannot be read from");
       System.out.println(f.canWrite() ? "File can be written to" : "File cannot be written to");
       System.out.println(f.isDirectory() ? "File is a directory" : "File is not a directory");
   }
}


Output:

File : FileDemo.java is a file
Size : 1557
Path : FileDemo.java
Absolute Path : D:\Java Examples\FileDemo.java
File was last modified : 1368414325890
File exists
File can be read from
File can be written to
File is not a directory

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.