Java File I/O

Reading from and writing to files using various I/O classes and streams

java (1.0+) 2025-11-03 file-io nio streams files

Description

Java provides multiple ways to read and write files, from the classic FileInputStream/FileOutputStream to modern NIO.2 Path API. Understanding different approaches helps choose the right tool for each task.

Approaches

  • Classic I/O: FileInputStream, FileOutputStream, FileReader, FileWriter
  • Buffered I/O: BufferedInputStream, BufferedWriter for better performance
  • NIO.2: Path, Files, Channels for modern file operations
  • Try-with-resources: Automatic resource management

Common Operations

  • Reading text files line by line
  • Writing text to files
  • Reading binary files
  • Copying and moving files
  • Directory operations

Code

RAW
import java.io.*;import java.nio.file.*;import java.util.*;import java.util.stream.Collectors;public class FileIOUtils {        // Read file using BufferedReader    public static List<String> readLines(String filename) throws IOException {        List<String> lines = new ArrayList<>();        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {            String line;            while ((line = reader.readLine()) != null) {                lines.add(line);            }        }        return lines;    }        // Read entire file as string    public static String readFile(String filename) throws IOException {        StringBuilder content = new StringBuilder();        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {            String line;            while ((line = reader.readLine()) != null) {                content.append(line).append("\n");            }        }        return content.toString();    }        // Write to file    public static void writeFile(String filename, String content) throws IOException {        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {            writer.write(content);        }    }        // Write lines to file    public static void writeLines(String filename, List<String> lines) throws IOException {        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {            for (String line : lines) {                writer.write(line);                writer.newLine();            }        }    }        // Read using NIO.2    public static List<String> readLinesNIO(String filename) throws IOException {        Path path = Paths.get(filename);        return Files.readAllLines(path);    }        // Write using NIO.2    public static void writeFileNIO(String filename, String content) throws IOException {        Path path = Paths.get(filename);        Files.write(path, content.getBytes());    }        // Copy file    public static void copyFile(String source, String dest) throws IOException {        Path sourcePath = Paths.get(source);        Path destPath = Paths.get(dest);        Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);    }        // Check if file exists    public static boolean fileExists(String filename) {        Path path = Paths.get(filename);        return Files.exists(path);    }}
RAW
// Read file line by linetry (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {    String line;    while ((line = reader.readLine()) != null) {        System.out.println(line);    }} catch (IOException e) {    e.printStackTrace();}// Write to filetry (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {    writer.write("Line 1");    writer.newLine();    writer.write("Line 2");} catch (IOException e) {    e.printStackTrace();}// Read entire file with NIO.2try {    Path path = Paths.get("input.txt");    List<String> lines = Files.readAllLines(path);    String content = String.join("\n", lines);} catch (IOException e) {    e.printStackTrace();}// Write with NIO.2try {    Path path = Paths.get("output.txt");    Files.write(path, "Hello World".getBytes());} catch (IOException e) {    e.printStackTrace();}// Copy filetry {    Files.copy(        Paths.get("source.txt"),        Paths.get("dest.txt"),        StandardCopyOption.REPLACE_EXISTING    );} catch (IOException e) {    e.printStackTrace();}// Read binary filetry (FileInputStream fis = new FileInputStream("image.jpg")) {    byte[] buffer = new byte[1024];    int bytesRead;    while ((bytesRead = fis.read(buffer)) != -1) {        // Process bytes    }} catch (IOException e) {    e.printStackTrace();}

Comments

No comments yet. Be the first to comment!