๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

File Class  


Introduction
  • The File class in Java is used to represent files and directories in the file system.
  • It allows you to create, delete, check and manage files and directories, but it does not handle file content directly.
  • The File class is present in the java.io package.
  • Syntax:
    public class File implements Serializable, Comparable
    {
        // constructors and methods
    }
    
Important Methods of File Class:
  • Below are some common and mostly used methods of File class with examples:
Method Description Example Output
createNewFile() Creates a new file if it does not exist.
File file = new File("example.txt");
if(file.createNewFile()){
    System.out.println("File created");
}else{
    System.out.println("File already exists");
}
File created / File already exists
exists() Checks whether the file or directory exists.
File file = new File("example.txt");
System.out.println(file.exists());
true / false
delete() Deletes the file or directory.
File file = new File("example.txt");
if(file.delete()){
    System.out.println("File deleted");
}else{
    System.out.println("Failed to delete");
}
File deleted / Failed to delete
getName() Returns the name of the file or directory.
File file = new File("example.txt");
System.out.println(file.getName());
example.txt
getAbsolutePath() Returns the absolute path of the file.
File file = new File("example.txt");
System.out.println(file.getAbsolutePath());
C:\Users\...\example.txt
isFile() Checks if it is a file.
File file = new File("example.txt");
System.out.println(file.isFile());
true / false
isDirectory() Checks if it is a directory.
File dir = new File("myFolder");
System.out.println(dir.isDirectory());
true / false
mkdir() Creates a new directory.
File dir = new File("myFolder");
if(dir.mkdir()){
    System.out.println("Directory created");
}else{
    System.out.println("Failed to create directory");
}
Directory created / Failed to create directory
list() Lists all files and directories inside a directory.
File dir = new File("myFolder");
String[] contents = dir.list();
for(String name : contents){
    System.out.println(name);
}
file1.txt
file2.txt
subFolder
Example:
  • import java.io.File;
    import java.io.IOException;
    
    public class FileExample
    {
        public static void main(String[] args)
        {
            try
            {
                File file = new File("example.txt");
    
                // Create a new file
                if(file.createNewFile())
                {
                    System.out.println("File created successfully.");
                }
                else
                {
                    System.out.println("File already exists.");
                }
    
                // Check if file exists
                if(file.exists())
                {
                    System.out.println("File exists at: " + file.getAbsolutePath());
                }
    
                // Delete the file
                if(file.delete())
                {
                    System.out.println("File deleted successfully.");
                }
                else
                {
                    System.out.println("Failed to delete file.");
                }
    
            }
            catch (IOException e)
            {
                System.out.println("An error occurred: " + e.getMessage());
            }
        }
    }

Example:
  1. The File class represents files or directories, but it does not store content. Use streams or readers/writers for reading/writing data.
  2. File paths can be relative or absolute. Relative paths are resolved from the current working directory.
  3. Creating a file or directory may fail due to permissions or if the parent directory doesn't exist.
  4. Deleting a directory will only succeed if the directory is empty.
  5. Always handle IOException when using methods like createNewFile() or accessing file paths.
  6. Use mkdirs() if you want to create nested directories along with missing parent directories.
  7. File operations are platform-dependent, e.g., path separators differ on Windows (\) and Linux/Mac (/).
  8. Checking existence (exists()) before performing operations like delete or create is a good practice to avoid errors.
  9. The File class provides metadata and file management only, not file content manipulation.