Skip to content
On this page

File Handling

Reading and Writing Files:

Java provides built-in classes for reading and writing files.

java
// Reading and writing files
import java.io.*;

// Writing to a file
try {
    FileWriter writer = new FileWriter("data.txt");
    writer.write("Hello, World!");
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

// Reading from a file
try {
    FileReader reader = new FileReader("data.txt");
    int character;
    while ((character = reader.read()) != -1) {
        System.out.print((char) character);
    }
    reader.close();
} catch (IOException e) {
    e.printStackTrace();
}

Working with Text Files:

Java provides BufferedReader and BufferedWriter classes to work with text files efficiently.

java
// Working with text files
import java.io.*;

// Writing to a text file
try {
    BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"));
    writer.write("Hello, World!");
    writer.newLine(); // Add a new line
    writer.write("This is a new line.");
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

// Reading from a text file
try {
    BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    reader.close();
} catch (IOException e) {
    e.printStackTrace();
}

Working with CSV and JSON Files:

To work with CSV and JSON files, you can use external libraries like Apache Commons CSV and Jackson JSON.

java
// Working with CSV files using Apache Commons CSV
import org.apache.commons.csv.*;

// Reading from a CSV file
try {
    CSVParser parser = CSVParser.parse(new File("data.csv"), CSVFormat.DEFAULT);
    for (CSVRecord record : parser) {
        String name = record.get(0);
        int age = Integer.parseInt(record.get(1));
        System.out.println("Name: " + name + ", Age: " + age);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// Writing to a CSV file
try {
    CSVPrinter printer = new CSVPrinter(new FileWriter("data.csv"), CSVFormat.DEFAULT);
    printer.printRecord("Alice", 30);
    printer.printRecord("Bob", 25);
    printer.printRecord("Eva", 28);
    printer.close();
} catch (IOException e) {
    e.printStackTrace();
}

// Working with JSON files using Jackson
import com.fasterxml.jackson.databind.ObjectMapper;

// Reading from a JSON file
try {
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> data = objectMapper.readValue(new File("data.json"), Map.class);
    System.out.println(data);
} catch (IOException e) {
    e.printStackTrace();
}

// Writing to a JSON file
try {
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> data = new HashMap<>();
    data.put("name", "Alice");
    data.put("age", 30);
    objectMapper.writeValue(new File("data.json"), data);
} catch (IOException e) {
    e.printStackTrace();
}