File Class in Advanced Java Programming

Home  »  Java  »  Advance Java »  Java File Handling »  File Class

The file class is used to deal with fiels and files system in Java. The File class helps determine the properties of a class such as the premissions to access the file, date and time when the file was created and directory path for the file. The File class hides the details how information is retrieved from and stored in files. Files can be used as source as well as destination to store the data for a program or the processed information obtained from the output of a program. Various constructors that can be used to create objects of the File class are:

  1. File(String directoryPath): The string parameter directory path determines the path name of the file.
  2. File(String diectoryPath, String filename): The string paramter directory path determines the path name of the file and the string parameter filename determines the name of the file.
  3. File(File dieObj, String filename): The file parameter dirObj determines the File object that specifies the directory and the string parameter filename determines the name of the file.
  4. file(URI uriObj): The URI parameter determines the URI object that describes a file.

Various examples of creating the File class objects based on the constructor are:

File file1=new File("/");

File file2=new File("/","autoexec.bat");

File file3=new File("file1","autoexec.bat");



The following program code shows how to obtain various properties of File Object.



The above example uses various methods such as getname to access the name of a file. The getAbsolutePath method determines the absolute path for the file. The exists function determines whether file exists or not. If the exists the function return true value and if the file does not exist the function returns false value and the above code will be stored in the file called FileClassTest.java, which on compilation will crate a class file called FileClassTest.class. Now compiple this file using below commands in the DOS mode:

C:\>jdk1.4\bin>javac FileClassTest.java
C:\>jdk1.4\bin>java FileClassTest



"Output of FileClassTest.class"


Download Complete Program

  -  



File Handling


Input/Output Streams I/O Exceptions
File Class File Input and Output Stream
Data Input and Output Stream Buffered Input and Output Streams
Reader and Writer Streams Random Access File



No comments:

Post a Comment