Skip to lesson

Text formats as the usual choice

A text format stores data as plain characters that people and programs can read, such as CSV, JSON or a properties file. Most programs today save and send data in a text format and keep Java serialization for a few special cases.

Readable, editable and language-neutral data

A language-neutral format can be read by programs in any language: Java, Python, JavaScript or a spreadsheet. A CSV line such as Priya,12,88 works everywhere; a .ser file works only in Java programs that have the exact class.

Example 1 · The same student saved two ways

TwoWaysDemo.javaJava
import java.io.IOException;import java.io.ObjectOutputStream;import java.io.Serializable;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
record Student(String name, int roll, int marks) implements Serializable {}
public class TwoWaysDemo {    public static void main(String[] args) throws IOException {        Student s = new Student("Priya", 12, 88);
        // Way 1: Java serialization        Path ser = Path.of("student.ser");        try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(ser))) {            out.writeObject(s);        }        byte[] bytes = Files.readAllBytes(ser);        System.out.printf("student.ser: %d bytes, starts with %02X %02X%n", bytes.length, bytes[0], bytes[1]);
        // Way 2: a CSV text line        Path csv = Path.of("student.csv");        Files.write(csv, List.of("name,roll,marks", s.name() + "," + s.roll() + "," + s.marks()),                StandardCharsets.UTF_8);        System.out.println("student.csv:");        for (String line : Files.readAllLines(csv, StandardCharsets.UTF_8)) {            System.out.println("  " + line);        }
        Files.delete(ser);        Files.delete(csv);    }}
Output
student.ser: 87 bytes, starts with AC ED
student.csv:
  name,roll,marks
  Priya,12,88

What this code does

  • The .ser file is binary: it starts with AC ED and holds the class description as well as the values.
  • The CSV file holds a header and one line that anyone can read, edit, or open in a spreadsheet.
  • Both files are deleted at the end so the program leaves nothing behind.

Text is also readable and editable. You can open it in Notepad, see what went wrong and fix one value by hand. With serialization, the class name, field names and values are mixed into binary bytes. Text also keeps code and data apart. Your program reads names and numbers and builds objects with its own constructors and checks, so the data cannot choose which classes run. That is why the Security lesson recommended it for data from outside.

CSV, JSON and properties compared

Each common text format fits a different shape of data. CSV holds rows that all have the same columns. JSON holds nested data: objects inside objects and lists. A properties file holds flat key=value settings.

Example 2 · One hostel room in CSV, JSON and properties form

ThreeFormatsDemo.javaJava
import java.util.List;
record Resident(String name, String city) {}
public class ThreeFormatsDemo {    static String toCsv(List<Resident> people) {        StringBuilder sb = new StringBuilder("name,city\n");        for (Resident r : people) {            sb.append(r.name()).append(',').append(r.city()).append('\n');        }        return sb.toString();    }
    static String toJson(String room, List<Resident> people) {        StringBuilder sb = new StringBuilder();        sb.append("{\n  \"room\": \"").append(room).append("\",\n  \"residents\": [\n");        for (int i = 0; i < people.size(); i++) {            Resident r = people.get(i);            sb.append("    {\"name\": \"").append(r.name()).append("\", \"city\": \"").append(r.city()).append("\"}");            sb.append(i < people.size() - 1 ? ",\n" : "\n");        }        sb.append("  ]\n}\n");        return sb.toString();    }
    public static void main(String[] args) {        List<Resident> people = List.of(new Resident("Ravi", "Nagpur"), new Resident("Sameer", "Kochi"));
        System.out.println("CSV (rows of the same shape):");        System.out.print(toCsv(people));
        System.out.println("JSON (nested data):");        System.out.print(toJson("B-204", people));
        System.out.println("Properties (flat settings):");        System.out.println("hostel.name=Kaveri Hostel");        System.out.println("hostel.curfew=22:00");    }}
Output
CSV (rows of the same shape):
name,city
Ravi,Nagpur
Sameer,Kochi
JSON (nested data):
{
  "room": "B-204",
  "residents": [
    {"name": "Ravi", "city": "Nagpur"},
    {"name": "Sameer", "city": "Kochi"}
  ]
}
Properties (flat settings):
hostel.name=Kaveri Hostel
hostel.curfew=22:00

What this code does

  • CSV fits the list of residents because every row has the same two columns.
  • JSON can hold the room and its nested list of residents in one piece.
  • Properties fit flat settings such as the hostel name and curfew time.

Example 3 · Read CSV by header name and properties with defaults

ReadBackDemo.javaJava
import java.io.IOException;import java.io.StringReader;import java.util.ArrayList;import java.util.List;import java.util.Properties;
record Resident(String name, String city) {}
public class ReadBackDemo {    public static void main(String[] args) throws IOException {        // CSV read by header name, so a new column does not break old code        String csv = "name,city,year\nRavi,Nagpur,2\nSameer,Kochi,3\n";        String[] lines = csv.split("\n");        List<String> header = List.of(lines[0].split(","));        int nameCol = header.indexOf("name");        int cityCol = header.indexOf("city");        List<Resident> people = new ArrayList<>();        for (int i = 1; i < lines.length; i++) {            String[] parts = lines[i].split(",");            people.add(new Resident(parts[nameCol], parts[cityCol]));        }        System.out.println("From CSV: " + people);
        // Properties with a default for a missing key        Properties settings = new Properties();        settings.load(new StringReader("hostel.name=Kaveri Hostel\nhostel.curfew=22:00\n"));        System.out.println("Name: " + settings.getProperty("hostel.name"));        System.out.println("Curfew: " + settings.getProperty("hostel.curfew"));        System.out.println("Wi-Fi: " + settings.getProperty("hostel.wifi", "not set"));    }}
Output
From CSV: [Resident[name=Ravi, city=Nagpur], Resident[name=Sameer, city=Kochi]]
Name: Kaveri Hostel
Curfew: 22:00
Wi-Fi: not set

What this code does

  • The CSV has a new year column. Because the code finds name and city by header name, the extra column does not break it.
  • Properties.load reads key=value lines; getProperty(key, default) returns the default when a key is missing.
  • CSV: tables such as marks, payments, attendance. Watch commas and quotes inside values.
  • JSON: nested data and data sent between apps over the internet.
  • Properties: program settings such as theme, port or file paths.

The JDK can read and write CSV with split and Files, and properties with java.util.Properties. It has no JSON reader: you write simple JSON by hand (the CSV module showed how), and real projects use a library such as Jackson or Gson to read it. Read CSV columns by header name, not by position. Then a file with a new column, or columns in a different order, still loads, much like a compatible change with serialVersionUID.

Where Java serialization still appears

Java serialization is still found where the same Java program writes and reads the bytes, and nobody else can touch them. One example is a quick deep copy: an independent copy of an object and everything inside it.

Example 4 · A deep copy with serialization (trusted, in memory)

DeepCopyDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.List;
class Timetable implements Serializable {    private static final long serialVersionUID = 1L;    String section;    List<String> periods = new ArrayList<>();
    Timetable(String section) {        this.section = section;    }}
public class DeepCopyDemo {    // Bytes made and read inside the same program: nothing untrusted is involved    static Timetable deepCopy(Timetable t) throws IOException, ClassNotFoundException {        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(t);        }        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            return (Timetable) in.readObject();        }    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {        Timetable cseA = new Timetable("CSE-A");        cseA.periods.add("Maths");        cseA.periods.add("DBMS");
        Timetable cseB = deepCopy(cseA);        cseB.section = "CSE-B";        cseB.periods.set(1, "Java Lab");
        System.out.println(cseA.section + ": " + cseA.periods);        System.out.println(cseB.section + ": " + cseB.periods);        System.out.println("Same list object? " + (cseA.periods == cseB.periods));    }}
Output
CSE-A: [Maths, DBMS]
CSE-B: [Maths, Java Lab]
Same list object? false

What this code does

  • deepCopy writes the timetable to bytes and reads it straight back, so the copy has its own list.
  • Changing the copy's list does not change the original, which a plain assignment would.
  • The bytes never leave the program, so there is no untrusted input. A copy constructor would do the same job with less work.

You will also meet it in older code: old Java desktop apps that saved files this way, remote calls between Java programs (RMI), and some older servers that copy user sessions between machines. When you maintain such code, keep the rules from this module: declare serialVersionUID, use transient, validate in readObject or use records, and add a filter. For new code, a text format or a copy constructor is usually simpler and safer.

Serializable versus a text format: how to choose

This comparison is a common interview question. A good answer names the trade-offs instead of saying one is always wrong.

  • Serializable: no extra code for big object graphs and shared references, but Java-only, binary, tied to the exact class, and dangerous with untrusted data.
  • Text format: a little more code to write and read, but readable, works in any language, easy to keep compatible, and your checks decide what is created.
  • Data that crosses a trust boundary or must last for years: text format.
  • Short-lived bytes inside one trusted Java program: serialization can be acceptable.

Next step

Check your understanding

12 quick questions