File Handling

Back

Loading concept...

📁 File Handling in Java: Your Computer’s Filing Cabinet

Imagine your computer is a giant filing cabinet. Inside it, you have folders (directories) and papers (files). Java gives you special tools to open drawers, read papers, write new notes, and organize everything perfectly!

Let’s become master file organizers together! 🗄️


🏠 The File Class: Your Map to Any File

Think of the File class as a treasure map. It doesn’t hold the treasure (the actual file content) — it just tells you WHERE the treasure is and WHAT it looks like!

What Can a File Object Tell You?

import java.io.File;

File myFile = new File("diary.txt");

// Does this file exist?
boolean exists = myFile.exists();

// What's its name?
String name = myFile.getName();

// Where exactly is it?
String path = myFile.getAbsolutePath();

// How big is it? (in bytes)
long size = myFile.length();

// Is it a file or a folder?
boolean isFile = myFile.isFile();
boolean isFolder = myFile.isDirectory();

Real Life Example:

  • You ask: “Is there a cookie jar in the kitchen?”
  • File class answers: “Yes! It’s on the counter, it’s blue, and it weighs 2 pounds!”
  • But it doesn’t give you cookies — just information ABOUT the jar!

✏️ File Operations: Reading and Writing

Now let’s actually OPEN that filing cabinet and DO things!

Creating a New File

File newFile = new File("myNote.txt");

if (newFile.createNewFile()) {
    System.out.println("File created!");
} else {
    System.out.println("File already exists.");
}

Like: Taking a fresh piece of paper and putting it in a folder!

Deleting a File

File oldFile = new File("oldStuff.txt");

if (oldFile.delete()) {
    System.out.println("Bye bye file!");
}

Like: Throwing a paper into the trash can! 🗑️

Renaming a File

File original = new File("cat.txt");
File newName = new File("kitten.txt");

original.renameTo(newName);

Like: Erasing “cat” and writing “kitten” on a folder label!


📂 Directory Operations: Organizing Your Folders

Directories are like boxes inside your filing cabinet. You can create them, look inside them, and organize them!

Creating a Directory

File folder = new File("MyPhotos");

// Create one folder
folder.mkdir();

// Create folder AND all parent folders
File deepFolder = new File("A/B/C/Photos");
deepFolder.mkdirs();

Simple Difference:

  • mkdir() = Make ONE box
  • mkdirs() = Make a box INSIDE a box INSIDE a box!

Listing Files in a Directory

File folder = new File("MyDocuments");
String[] files = folder.list();

for (String fileName : files) {
    System.out.println(fileName);
}

Like: Opening a drawer and reading every label inside!

Getting File Objects (Not Just Names)

File folder = new File("MyDocuments");
File[] allFiles = folder.listFiles();

for (File f : allFiles) {
    System.out.println(f.getName() +
        " - Size: " + f.length());
}

🛤️ Path and Paths: The Modern GPS

The old File class is like an old paper map. Path and Paths are like a GPS — smarter, faster, and more powerful!

Creating Paths

import java.nio.file.Path;
import java.nio.file.Paths;

// Method 1: Using Paths helper
Path path1 = Paths.get("documents/notes.txt");

// Method 2: Using Path.of (Java 11+)
Path path2 = Path.of("documents", "notes.txt");

// Get different parts
String fileName = path1.getFileName().toString();
Path parent = path1.getParent();
Path fullPath = path1.toAbsolutePath();

GPS Powers:

Path base = Paths.get("/home/user");
Path file = Paths.get("docs/file.txt");

// Combine paths (like GPS directions!)
Path combined = base.resolve(file);
// Result: /home/user/docs/file.txt

// Find the way from one place to another
Path from = Paths.get("/home/user/photos");
Path to = Paths.get("/home/user/docs");
Path howToGet = from.relativize(to);
// Result: ../docs

🚀 The Files Class: Your Super-Powered File Tool

If Path is your GPS, then Files is your robot assistant that does ALL the work for you!

Reading Files (So Easy!)

import java.nio.file.Files;
import java.nio.file.Path;

Path path = Path.of("story.txt");

// Read ALL lines at once
List<String> lines = Files.readAllLines(path);

// Read as one big string
String content = Files.readString(path);

// Read as bytes
byte[] data = Files.readAllBytes(path);

Like: Asking your robot to read you a bedtime story!

Writing Files

Path path = Path.of("diary.txt");

// Write a string
Files.writeString(path, "Dear diary...");

// Write lines
List<String> lines = List.of(
    "Line 1",
    "Line 2",
    "Line 3"
);
Files.write(path, lines);

Copying and Moving

Path source = Path.of("photo.jpg");
Path backup = Path.of("backup/photo.jpg");

// Copy a file
Files.copy(source, backup);

// Move a file
Files.move(source, Path.of("archive/photo.jpg"));

Like: Your robot picks up the paper and carries it to a new folder!

Checking File Properties

Path path = Path.of("secret.txt");

boolean exists = Files.exists(path);
boolean canRead = Files.isReadable(path);
boolean canWrite = Files.isWritable(path);
boolean isHidden = Files.isHidden(path);
long size = Files.size(path);

🌟 NIO Basics: The New Way to Handle Files

NIO stands for New Input/Output. Think of it as the upgraded, super-fast version of file handling!

The Key Players

graph TD A["NIO System"] --> B["Path"] A --> C["Files"] A --> D["Channels"] A --> E["Buffers"] B --> F["Where is my file?"] C --> G["Do stuff with files!"] D --> H["Fast data pipes"] E --> I["Data containers"]

Channels and Buffers: Speed Mode! 🏎️

Think of:

  • Channel = A highway for data
  • Buffer = A truck carrying data on the highway
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;

Path path = Path.of("bigdata.bin");

// Reading with channel
try (FileChannel channel =
     FileChannel.open(path, StandardOpenOption.READ)) {

    ByteBuffer buffer = ByteBuffer.allocate(1024);
    channel.read(buffer);
    buffer.flip(); // Ready to read from buffer

    while (buffer.hasRemaining()) {
        byte b = buffer.get();
        // Process byte...
    }
}

Why Use NIO?

Old Way (IO) New Way (NIO)
Read one byte at a time Read chunks at once
Blocks until done Can do other things while waiting
Good for small files Great for BIG files!

Walking Through Directories

// Visit every file in a folder tree!
Files.walk(Path.of("myFolder"))
    .filter(Files::isRegularFile)
    .forEach(System.out::println);

// With more control
Files.walkFileTree(Path.of("myFolder"),
    new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(
            Path file, BasicFileAttributes attrs) {
            System.out.println("Found: " + file);
            return FileVisitResult.CONTINUE;
        }
    });

Like: A robot that walks through EVERY room in your house and tells you what it finds!


🎯 Quick Summary

What Class Use For
File location info File Basic file/folder info
Modern file path Path Smart path handling
Create Path easily Paths.get() Making paths
File operations Files Read, write, copy, move
Fast data transfer Channel Big files, speed
Data container Buffer Holding data chunks

💡 Remember This!

  1. File = The old map (still works, but old-school)
  2. Path = The modern GPS (smarter navigation)
  3. Files = Your robot helper (does all the work!)
  4. NIO = The super-highway (fast and powerful)

You’re now ready to organize ANY files like a pro! Your computer’s filing cabinet has no secrets from you! 🎉


Happy file handling! Remember: Every big program started with someone who learned to read and write files!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.