Java File class

Introduction

File class deals with files and the file system.

File class describes the properties of a file itself.

A File object can get and set the file information such as the permissions, time, date.

We can navigate subdirectory hierarchies via File object.

The Path interface and Files class from java.nio packages offer a powerful alternative to File.

A directory in Java is treated as a File.

We can get a list of filenames from a folder by the list() method.

The following constructors can be used to create File objects:

File(String directoryPath)  
File(String directoryPath, String filename )  
File(File dirObj, String filename )  
File(URI uriObj)                                                                                       

The following example creates three files: f1, f2, and f3.


File f1 = new File("/");  
File f2 = new File("/","autoexec.bat");  
File f3 = new File(f1,"autoexec.bat"); //same as f2

If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

To use the Windows convention of a backslash character (\), use its escape sequence (\\) within a string.

// Demonstrate File. 
import java.io.File; 
 
public class Main { 
  public static void main(String args[]) { 
    File f1 = new File("./Main.java"); 
 
    System.out.println("File Name: " + f1.getName()); 
    System.out.println("Path: " + f1.getPath()); 
    System.out.println("Abs Path: " + f1.getAbsolutePath()); 
    System.out.println("Parent: " + f1.getParent()); 
    System.out.println(f1.exists() ? "exists" : "does not exist"); 
    System.out.println(f1.canWrite() ? "is writeable" : "is not writeable"); 
    System.out.println(f1.canRead() ? "is readable" : "is not readable"); 
    System.out.println("is " + (f1.isDirectory() ? "" : "not" + " a directory")); 
    System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe"); 
    System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute"); 
    System.out.println("File last modified: " + f1.lastModified()); 
    System.out.println("File size: " + f1.length() + " Bytes"); 
  } //from ww  w .java  2 s  .co  m
}



PreviousNext

Related