Java.Which class is designed to work with file system elements?

📁 java.io.File


🧠 What is File?

  • It’s a class in the java.io package.
  • It represents a file or directory path in an abstract, platform-independent way.
  • It does not read/write file content itself — it provides metadata and file system operations.

🔧 Key Features

MethodPurpose
exists()Checks if file or directory exists
createNewFile()Creates a new empty file
mkdir() / mkdirs()Creates one or multiple directories
delete()Deletes the file/directory
renameTo(File dest)Renames/moves the file
length()Returns file size in bytes
list() / listFiles()Lists directory contents
isDirectory() / isFile()Checks type
getAbsolutePath()Returns full path
lastModified()Gets last modified timestamp

✅ Example: Using File

import java.io.File;

public class FileDemo {
    public static void main(String[] args) {
        File file = new File("test.txt");

        if (!file.exists()) {
            try {
                file.createNewFile();
                System.out.println("File created: " + file.getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println("Is it a file? " + file.isFile());
        System.out.println("Size: " + file.length() + " bytes");
    }
}

📂 Bonus: java.nio.file.Path & Files

Since Java 7, there’s a newer and more powerful API for working with files:

📘 java.nio.file.Path and java.nio.file.Files

They offer:

  • Better performance
  • More fine-grained control
  • Support for symbolic links, file attributes, etc.

Example:

import java.nio.file.*;

Path path = Paths.get("test.txt");
Files.createFile(path);
System.out.println("Exists? " + Files.exists(path));

🧵 Summary

ClassPurpose
java.io.FileWork with file/directory paths and metadata
java.nio.file.Path + FilesModern file system API (preferred for complex tasks)
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.