Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

Read File/Folder Attributes

Problem - How you can identify attributes of a file/folder that exist on your hard drive? Attributes are read access, write access, last modified date, created date, file size etc.

Solution :
File/Folder attributes can be identified by a java class  java.io.File.  Below is sample program.

Program :

Step 1 - Coding

Create a text file c:\sunilos\Attrib.java  and copy below contents.

import java.io.File;
import java.util.Date;
import java.io.*;
import java.util.*;

public class Attrib {

    public static void main(String[] args) {
    File f =new File("c:/sunilos/sunilos.txt");
        System.out.println("Name " + f.getName());
        System.out.println("Absolute path: " +f.getAbsolutePath());
        System.out.println("Is writable " +f.canWrite());
        System.out.println("Is readable " + f.canRead());
        System.out.println("Is File " + f.isFile());
        System.out.println("Is Directory " + f.isDirectory());
        System.out.println("Last Modified at " + new Date(f.lastModified()));
        System.out.println("Length " + f.length() +"bytes long.");

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy Attrib.java into 'c:\sunilos' folder.
  3. It is assumed that your hard drive has c:/sunilos/sunilos.txt file and you want to see it's attributes
  4. Open your command prompt and go to  'c:\sunilos'
  5. Compile Attrib.java with help of
    •  javac Attrib.java command.  Command will create Attrib.class file in the same folder.
  6. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java Attrib command.


Name sunilos.txt
Absolute path: c:\sunilos\sunilos.txt
Is writable true
Is readable true
Is File true
Is Directory false
Last Modified at Sat Mar 14 11:45:28 GMT+05:30 2009
Length 1741bytes long.


Most Interesting methods?

  • canRead() - Tests whether the application can read the file denoted by this abstract pathname.
  • canWrite() - Tests whether the application can modify to the file denoted by this abstract pathname.
  • getAbsolutePath() - Returns the absolute pathname string of this abstract pathname.
  • getName() - Returns the name of the file or directory denoted by this abstract pathname.
  • getPath() - Converts this abstract pathname into a pathname string.
  • isDirectory() - Tests whether the file denoted by this abstract pathname is a directory.
  • isFile() - Tests whether the file denoted by this abstract pathname is a normal file.
  • lastModified() - Returns the time that the file denoted by this abstract pathname was last modified.
  • length() Returns the length of the file denoted by this abstract pathname.

<<Previous | Next>>
Namrata Sisodiya,
Aug 19, 2011, 10:05 PM