DEV Community

Sudhakar V
Sudhakar V

Posted on

File Handling in Java

Java provides several ways to handle files through its I/O (Input/Output) packages. Here's a comprehensive overview of file handling in Java:

Core Classes for File Handling

Java's file handling capabilities are primarily in the java.io and java.nio packages.

1. java.io Package (Traditional I/O)

  • File: Represents file and directory pathnames
  • FileInputStream/FileOutputStream: For byte-oriented input/output
  • FileReader/FileWriter: For character-oriented input/output
  • BufferedReader/BufferedWriter: For buffered character I/O
  • PrintWriter: For formatted output

2. java.nio Package (New I/O)

  • Path: Interface replacing File class
  • Paths: Factory methods for creating Path objects
  • Files: Utility methods for file operations
  • FileChannel: For high-performance file operations

Basic File Operations

1. Creating a File

import java.io.File;
import java.io.IOException;

public class CreateFile {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Writing to a File

Using FileWriter:

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

public class WriteToFile {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("example.txt");
            writer.write("Hello, World!");
            writer.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Using BufferedWriter (more efficient):

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

public class BufferedWrite {
    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
            writer.write("Hello, World!");
            writer.newLine();  // Adds a new line
            writer.write("This is a new line.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Reading from a File

Using FileReader:

import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("example.txt");
            int character;
            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Using BufferedReader (more efficient):

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedRead {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Deleting a File

import java.io.File;

public class DeleteFile {
    public static void main(String[] args) {
        File file = new File("example.txt");
        if (file.delete()) {
            System.out.println("Deleted the file: " + file.getName());
        } else {
            System.out.println("Failed to delete the file.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Using java.nio Package (New I/O)

1. Reading a File

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;

public class ReadFileNIO {
    public static void main(String[] args) {
        try {
            List<String> lines = Files.readAllLines(Paths.get("example.txt"));
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Writing to a File

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class WriteFileNIO {
    public static void main(String[] args) {
        List<String> lines = Arrays.asList("First line", "Second line", "Third line");
        try {
            Files.write(Paths.get("example.txt"), lines);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Checking File Properties

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class FileProperties {
    public static void main(String[] args) {
        Path path = Paths.get("example.txt");
        System.out.println("File exists: " + Files.exists(path));
        System.out.println("Is directory: " + Files.isDirectory(path));
        System.out.println("Is readable: " + Files.isReadable(path));
        System.out.println("Is writable: " + Files.isWritable(path));
        try {
            System.out.println("Size: " + Files.size(path) + " bytes");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Use try-with-resources: Automatically closes resources
   try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
       // use the resource
   } catch (IOException e) {
       e.printStackTrace();
   }
Enter fullscreen mode Exit fullscreen mode
  1. Handle exceptions properly: Don't just print stack traces

  2. Use buffered streams for better performance with large files

  3. Consider NIO for more complex file operations and better performance

  4. Specify character encoding when working with text files to avoid platform-dependent issues

   new InputStreamReader(new FileInputStream("file.txt"), StandardCharsets.UTF_8);
Enter fullscreen mode Exit fullscreen mode
  1. Check file existence before operations when necessary

Serialization (Object to File)

Java allows writing objects directly to files through serialization:

import java.io.*;

class Person implements Serializable {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class SerializationExample {
    public static void main(String[] args) {
        // Serialization
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
            Person p = new Person("John", 30);
            oos.writeObject(p);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Deserialization
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
            Person p = (Person) ois.readObject();
            System.out.println("Name: " + p.name + ", Age: " + p.age);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This covers the fundamental aspects of file handling in Java. The approach you choose (traditional I/O vs NIO) depends on your specific requirements and Java version compatibility needs.

Top comments (0)