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"); if(f.exists()){ 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."); }//if }//main }//class Step 2 - Deployment - Create a folder 'c:\sunilos'.
- Create or copy Attrib.java into 'c:\sunilos' folder.
- It is assumed that your hard drive has c:/sunilos/sunilos.txt file and you want to see it's attributes
- Open your command prompt and go to 'c:\sunilos'
- Compile Attrib.java with help of
- javac Attrib.java command. Command will create Attrib.class file in the same folder.
- Congratulations!! your Java program is ready to serve.
Step 3 - Testing- Make sure you are on Command Prompt under c:\sunilos directory
- Now start your java program from command prompt with help of
OutputName 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. |
FAQMost 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>> |
 Updating...
Mahima Hardia, Aug 19, 2011, 10:05 PM
|