Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Files and I/O

Java Structured Data: Reading and Writing JSON and CSV

Two Student records, Emma Clark with 91 in Java and Liam Brown with 78 in SQL, saved two ways. Jackson's ObjectMapper writes them to students.json and reads them back in one call each; plain Java writes students.csv with a header and reads it back by splitting at the commas.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Files and I/O

What you will learn

  • Describe how the same records look as JSON and as CSV
  • Write a list of records to JSON and read it back with Jackson's ObjectMapper
  • Write a CSV file with a header and comma-joined lines using Files.write
  • Read a CSV file by skipping the header, splitting and parsing

Before you start

  • Reading and writing text files in Java
  • Java records

Imagine a record for every student, with a name, a course and a score, and thousands of them to save and load again. Two common text formats do the job: JSON and CSV. Every example uses this record:

package org.studyeasy.s07l03;

// One student: the same three values in JSON and in CSV
public record Student(String name, String course, int score) {}

The same two students, two ways

Here are Emma Clark (Java, 91) and Liam Brown (SQL, 78) as JSON:

[ {
  "name" : "Emma Clark",
  "course" : "Java",
  "score" : 91
}, {
  "name" : "Liam Brown",
  "course" : "SQL",
  "score" : 78
} ]

And as CSV:

name,course,score
Emma Clark,Java,91
Liam Brown,SQL,78

In JSON, square brackets hold a list and each pair of curly braces is one student, with every value named by a key. CSV is a header line with the column names, then one line per student with commas between the values. Both are plain text, so any program can read them.

Write JSON

package org.studyeasy.s07l03;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.List;

public class Ex01_WriteJson {
    public static void main(String[] args) throws Exception {
        List<Student> students = List.of(
                new Student("Emma Clark", "Java", 91),
                new Student("Liam Brown", "SQL", 78));

        // Jackson's ObjectMapper turns objects into JSON
        ObjectMapper mapper = new ObjectMapper();
        mapper.writerWithDefaultPrettyPrinter()
                .writeValue(new File("students.json"), students);
        System.out.println("Saved students.json");
    }
}
Saved students.json

Java has no built-in JSON writer, so the project adds Jackson (jackson-databind) through its pom.xml. An ObjectMapper takes objects in and gives JSON text out. One writeValue call writes the whole list: each record becomes one { } block, and the pretty printer adds the line breaks shown above.

Read JSON

ObjectMapper mapper = new ObjectMapper();
// a JSON array [ ... ] comes back as an array
Student[] students = mapper.readValue(
        new File("students.json"), Student[].class);
for (Student student : students) {
    System.out.println(student);
}
Student[name=Emma Clark, course=Java, score=91]
Student[name=Liam Brown, course=SQL, score=78]
Writing: a List of two Student records goes into ObjectMapper.writeValue and comes out as students.json, one curly-brace block per record. Reading: students.json goes into ObjectMapper.readValue with Student[].class, and comes back as a Student array of Emma Clark and Liam Brown. Student recordsEmma, Liam ObjectMapperJackson students.json[ { }, { } ] writeValue: objects in, JSON out readValue(file, Student[].class): JSON in, objects out
One call each way: the class you pass tells Jackson what to build from each block.

readValue takes the file and Student[].class, which tells Jackson what to build from each block. The keys match the record's component names, so each block becomes a Student again, and the record's own toString prints it. Run Ex01 first so the file exists.

Write CSV

List<String> lines = new ArrayList<>();
lines.add("name,course,score");          // the header row
for (Student s : students) {
    lines.add(s.name() + "," + s.course() + "," + s.score());
}
Files.write(Path.of("students.csv"), lines);
System.out.println("Saved students.csv");
Saved students.csv

This one is plain Java. A CSV file is just lines of text, so we build a List<String>: the header first, then each student's values joined with commas. Files.write saves all the lines in one call.

Read CSV

Path file = Path.of("students.csv");
List<String> lines = Files.readAllLines(file);

// line 0 is the header, so start at 1
for (int i = 1; i < lines.size(); i++) {
    String[] cells = lines.get(i).split(",");
    String name = cells[0];
    int score = Integer.parseInt(cells[2]);
    System.out.println(name + ": " + score);
}
Emma Clark: 91
Liam Brown: 78

readAllLines gives three strings. The loop starts at 1 to skip the header; start at 0 and parseInt meets the word "score", throwing NumberFormatException. split(",") cuts a line into cells, and every cell is text until you parse it. This simple split assumes no value contains a comma.

JSON or CSV?

JSONCSV
One student{ "name" : "Emma Clark", ... }Emma Clark,Java,91
Labelsevery value has a keythe header names the columns
Write and readwriteValue, readValue (Jackson)Files.write, split(",")
Good forobjects, nested data, web APIstables, spreadsheets

Rows and columns: CSV. Anything with more shape: JSON. Either way, it's text you save and read back.

Keep going in Java · 79 of 79

Previous
Reading and Writing Text Files in Java
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Files and Directories with NIO.2: Path and Files

Path.of("invoices", "2026", "inv-101.pdf") is only an address: getFileName, getParent and resolve work, but nothing is on disk. Files.createDirectories and createFile make an order file and delete removes it, Files.walk finds 4 .java files, and os.name tells Windows from Linux.

Reading and Writing Text Files in Java

Files.readString reads tasks.txt in one call and readAllLines splits it into three tasks. writeString makes a shopping list that Files.lines filters to 2 items starting with B, a BufferedWriter writes an invoice, a Scanner totals 257, and Café is 4 characters but 5 bytes.

On this page

  • The same two students, two ways
  • Write JSON
  • Read JSON
  • Write CSV
  • Read CSV
  • JSON or CSV?
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.