Java File Handling: Creating, Reading, Writing & Managing Files

package Pack1;
import java.io.File;
import java.io.IOException;

public class my_file {
    public static void main(String[] args) {
        try {
            File my_file_obj = new File("my_new_file.txt");
            if (my_file_obj.createNewFile()) {
                System.out.println("New File created: " + my_file_obj.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("Oops some error.");
            e.printStackTrace();
        }
    }
}

Output (First Run):

New File created: my_new_file.txt

1. Essential Methods of java.io.File 🔝

Method Return Type Behavior
createNewFile() boolean Atomically creates a new empty file if it does not exist yet (throws IOException).
exists() boolean Returns true if the file or directory exists on disk.
length() long Returns the file size in bytes (or 0L if the file does not exist).
getAbsolutePath() String Returns the full resolved path from the filesystem root.
mkdir() / mkdirs() boolean Creates a single directory (mkdir) or including missing parent folders (mkdirs).
delete() boolean Deletes the file (or empty directory) and returns true on success.

2. Custom File Locations & Cross-Platform file.separator 🔝

When you pass a relative name like new File("my_new_file.txt"), Java creates the file in your current working/project directory (e.g., C:\Users\user_name\eclipse-workspace\java_projects). For custom folders:

  • Windows path (escaped backslashes): new File("D:\\java_files\\my_new_file.txt")
  • Linux / macOS path: new File("/Users/java_files/my_new_file.txt")
  • Universal OS-independent path: Query System.getProperty("file.separator") (or File.separator):
package Pack1;
import java.io.File;
import java.io.IOException;

public class my_file {
    public static void main(String[] args) {
         // Cross-platform separator ("\" on Windows, "/" on Linux/macOS):
        String my_separator = System.getProperty("file.separator");  // or File.separator
        String my_path = "D:" + my_separator + "java_files" + my_separator;
        System.out.println("Universal Path: " + my_path + "my_new_file2.txt");
    }
}

Terminal Output:

Universal Path: D:/java_files/my_new_file2.txt

3. Writing Text to a File with FileWriter (try-with-resources) 🔝

Note that new File(...) only represents the file path; to write text into the file, wrap FileWriter in a try (...) block so the stream is flushed and closed automatically:

import java.io.FileWriter;
import java.io.IOException;

public class WriteFileDemo {
    public static void main(String[] args) {
         // try-with-resources automatically flushes and closes FileWriter!
        try (FileWriter writer = new FileWriter("my_new_file.txt")) {
            writer.write("Welcome to plus2net Java File Handling!\n");
            writer.write("Second line of text.");
            System.out.println("Successfully wrote text to my_new_file.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Terminal Output:

Successfully wrote text to my_new_file.txt

4. Reading a File Line by Line with Scanner 🔝

Passing your File object to new Scanner(my_file_obj) inside a while (reader.hasNextLine()) loop reads the file line by line:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFileDemo {
    public static void main(String[] args) {
        File my_file_obj = new File("my_new_file.txt");
        try (Scanner reader = new Scanner(my_file_obj)) {
            while (reader.hasNextLine()) {
                System.out.println(reader.nextLine());
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
        }
    }
}

Terminal Output:

Welcome to plus2net Java File Handling!
Second line of text.

5. Inspecting File Existence, Permissions & Byte Size 🔝

Before reading or deleting a file, you can inspect its attributes using exists(), canRead(), canWrite(), and length():

import java.io.File;

public class FileMetadataDemo {
    public static void main(String[] args) {
        File f = new File("my_new_file.txt");
        if (f.exists()) {
            System.out.println("File Name: " + f.getName());
            System.out.println("Readable:  " + f.canRead() + " | Writable: " + f.canWrite());
            System.out.println("Size:      " + f.length() + " bytes");
        }
    }
}

Terminal Output:

File Name: my_new_file.txt
Readable:  true | Writable: true
Size:      60 bytes

6. Modern Java 11+ One-Line Read & Write (java.nio.file.Files) 🔝

In modern Java (Java 11+), java.nio.file.Files.writeString() and Files.readString() read and write UTF-8 text files in a single line:

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

public class ModernNioFileDemo {
    public static void main(String[] args) throws Exception {
        Path p = Path.of("nio_sample.txt");
        Files.writeString(p, "One-line write & read with java.nio.file.Files!");
        System.out.println(Files.readString(p));
        Files.deleteIfExists(p);
    }
}

Terminal Output:

One-line write & read with java.nio.file.Files!

7. Comparison: Classic java.io.File vs Modern java.nio.file.Path 🔝

Feature java.io.File java.nio.file.Path & Files
Error Reporting Returns false silently on delete() Throws descriptive IOException on failure
One-Line Text Read/Write Requires FileWriter / Scanner Built-in (Files.readString / writeString)
Symbolic Links & Copy Limited support Full support (Files.copy(), Files.move())

8. Common Developer Pitfalls & Traps 🔝

Unescaped Backslashes in Windows Paths: "D: ew_file.txt"

In Java string literals, is interpreted as a newline character and as a tab! Writing new File("D: ew_file.txt") corrupts the filename. Always escape backslashes as "D:\\new_file.txt", use forward slashes "D:/new_file.txt" (which Java supports on Windows too!), or use File.separator.

IOException: The System Cannot Find the Path Specified

my_file_obj.createNewFile() throws an IOException if the parent directory (such as D:\java_files) does not exist yet! Call my_file_obj.getParentFile().mkdirs(); before calling createNewFile().

9. Complete Compilable Java Program 🔝

import java.io.File;
import java.io.FileWriter;

public class FileHandlingFullDemo {
    public static void main(String[] args) throws Exception {
        File temp = new File("test_verify.txt");
        try (FileWriter fw = new FileWriter(temp)) {
            fw.write("plus2net");
        }
        if (temp.exists() && temp.length() == 8 && temp.delete()) {
            System.out.println("All Java File create, write, length & delete checks passed!");
        }
    }
}

Terminal Output:

All Java File create, write, length & delete checks passed!

10. Frequently Asked Questions (FAQ) 🔝

Does new File("my_new_file.txt") create a file on disk immediately?

No! The new File(...) constructor only creates an in-memory path object. The actual file is created on disk only when you call createNewFile() or open a FileWriter / FileOutputStream.

How do I append text to an existing file instead of overwriting it?

Pass true as the second argument to the FileWriter constructor: new FileWriter("my_new_file.txt", true).

Does createNewFile() overwrite an existing file?

No, createNewFile() is safe: if the file already exists, it leaves the existing file untouched and simply returns false.

Why did my_file_obj.delete() return false on a directory?

In Java, File.delete() can only delete a directory if the directory is completely empty. You must delete all files inside the folder first.

How do I convert between java.io.File and java.nio.file.Path?

Call my_file_obj.toPath() to convert a File to a Path, or myPath.toFile() to convert a Path back to a File.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer