נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
29
חלקPart 5: Java מודרנית וכליםModern Java & tools כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

קבצים עם NIO ו-JSONFiles with NIO & JSON

Path ו-Files, קריאה וכתיבה של טקסט, CSV, ושמירה וטעינה של JSON.

Path and Files, reading and writing text, CSV, and saving and loading JSON.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • Path: כתובת של קובץ או תיקייה: Path.of("library", "scifi"). נתיב יחסי מתחיל מהתיקייה שבה התוכנית רצה.Path: The address of a file or folder: Path.of("library", "scifi"). A relative path starts from the folder the program runs in.
  • Files: מחלקת עזר עם כל הפעולות: writeString, readString, write, readAllLines, lines, exists, size, createDirectories, list, delete. רובן זורקות IOException (checked).Files: A utility class with all the operations: writeString, readString, write, readAllLines, lines, exists, size, createDirectories, list, delete. Most throw IOException (checked).
  • CSV: קובץ טקסט שבו כל שורה היא רשומה ושדות מופרדים בפסיק (או ;). פשוט, אבל צריך להיזהר מפסיק בתוך שדה.CSV: A text file where each line is a record and fields are separated by a comma (or ;). Simple, but watch out for a comma inside a field.
  • JSON: פורמט טקסט לנתונים: {"title": "Dune", "year": 1965}, ומערכים ב-[...]. בפרויקט אמיתי משתמשים ב-Jackson או Gson, שממירים record ל-JSON ובחזרה בשורה אחת.JSON: A text format for data: {"title": "Dune", "year": 1965}, with arrays in [...]. Real projects use Jackson or Gson, which turn a record into JSON and back in one line.
  • NoSuchFileException: החריגה כשקוראים קובץ שלא קיים. היא IOException, כלומר checked.NoSuchFileException: The exception when reading a file that doesn't exist. It's an IOException, so it's checked.

02לכתוב ולקרוא קובץWriting and reading a file

Files עושה את כל העבודה: writeString יוצר את הקובץ, readAllLines מחזיר רשימת שורות. main מכריז throws IOException, כי פעולות על קבצים יכולות להיכשל.

Files does all the work: writeString creates the file, readAllLines returns a list of lines. main declares throws IOException, because file operations can fail.

Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("shelf.txt");
        System.out.println(Files.exists(p));
        Files.writeString(p, "Dune;1965\nEmma;1815\n");
        List<String> lines = Files.readAllLines(p);
        System.out.println(lines);
        System.out.println(Files.exists(p) + " " + Files.size(p) + " bytes");
    }
}
פלטOutput
false
[Dune;1965, Emma;1815]
true 20 bytes
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03להוסיף לסוף, ולקרוא כזרםAppending, and reading as a stream

StandardOpenOption.APPEND מוסיף לסוף במקום לדרוס. Files.lines מחזיר Stream של שורות שמחזיק את הקובץ פתוח, ולכן הוא ב-try-with-resources.

StandardOpenOption.APPEND adds to the end instead of overwriting. Files.lines returns a Stream of lines that keeps the file open, so it goes in a try-with-resources.

Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.nio.file.StandardOpenOption;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) throws IOException {
        Path log = Path.of("log.txt");
        Files.write(log, List.of("start"));
        Files.writeString(log, "added Dune\n", StandardOpenOption.APPEND);
        Files.writeString(log, "added Emma\n", StandardOpenOption.APPEND);
        try (Stream<String> s = Files.lines(log)) {
            System.out.println(s.filter(l -> l.startsWith("added")).count() + " additions");
        }
        System.out.print(Files.readString(log));
    }
}
פלטOutput
2 additions
start
added Dune
added Emma
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04JSON בידJSON by hand

JSON הוא רק טקסט עם כללים: מחרוזות במירכאות, ומירכאות בתוך מחרוזת צריך לסמן ב-\". כאן כותבים אותו ביד כדי להבין את המבנה. במחשב שלכם, Jackson עושה את זה בשורה: new ObjectMapper().writeValueAsString(book).

JSON is just text with rules: strings in quotes, and quotes inside a string must be escaped as \". Here we write it by hand to understand the shape. On your computer, Jackson does it in one line: new ObjectMapper().writeValueAsString(book).

Main.java
import java.util.List;

public class Main {
    static String json(Book b) {
        return "{\"title\": \"" + escape(b.title()) + "\", \"year\": " + b.year() + "}";
    }

    static String escape(String s) {
        return s.replace("\\", "\\\\").replace("\"", "\\\"");
    }

    public static void main(String[] args) {
        List<Book> books = List.of(new Book("Dune", 1965), new Book("The \"Odyssey\"", -700));
        StringBuilder out = new StringBuilder("[\n");
        for (int i = 0; i < books.size(); i++) {
            out.append("  ").append(json(books.get(i))).append(i < books.size() - 1 ? ",\n" : "\n");
        }
        System.out.print(out.append("]\n"));
    }
}

record Book(String title, int year) {
}
פלטOutput
[
  {"title": "Dune", "year": 1965},
  {"title": "The \"Odyssey\"", "year": -700}
]
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05קובץ שלא קייםA file that doesn't exist

קוראים קובץ שאף אחד לא יצר, ומקבלים NoSuchFileException.

Reading a file nobody created gives a NoSuchFileException.

טעות נפוצהCommon mistake

קובץ שלא קיים

A file that doesn't exist

Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("books.txt");
        List<String> lines = Files.readAllLines(p);
        System.out.println(lines.size() + " books");
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
Exception in thread "main" java.nio.file.NoSuchFileException: books.txt
	at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
	at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:106)
	at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
	at java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:261)
	at java.base/java.nio.file.Files.newByteChannel(Files.java:380)
	at java.base/java.nio.file.Files.newByteChannel(Files.java:432)
	at java.base/java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:420)
	at java.base/java.nio.file.Files.newInputStream(Files.java:160)
	at java.base/java.nio.file.Files.newBufferedReader(Files.java:2910)
	at java.base/java.nio.file.Files.readAllLines(Files.java:3405)
	at java.base/java.nio.file.Files.readAllLines(Files.java:3446)
	at Main.main(Main.java:9)
בעברית פשוטה: In plain words: java.nio.file.NoSuchFileException: books.txt: בודקים קודם עם Files.exists, או תופסים את החריגה.java.nio.file.NoSuchFileException: books.txt: check first with Files.exists, or catch the exception.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.

These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.

טעות נפוצהCommon mistake

צייד באגים: קובץ חסר

Bug hunter: a missing file

Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("books.txt");
        List<String> lines = Files.readAllLines(p);
        System.out.println(lines.size() + " books");
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
Exception in thread "main" java.nio.file.NoSuchFileException: books.txt
	at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
	at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:106)
	at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
	at java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:261)
	at java.base/java.nio.file.Files.newByteChannel(Files.java:380)
	at java.base/java.nio.file.Files.newByteChannel(Files.java:432)
	at java.base/java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:420)
	at java.base/java.nio.file.Files.newInputStream(Files.java:160)
	at java.base/java.nio.file.Files.newBufferedReader(Files.java:2910)
	at java.base/java.nio.file.Files.readAllLines(Files.java:3405)
	at java.base/java.nio.file.Files.readAllLines(Files.java:3446)
	at Main.main(Main.java:9)
בעברית פשוטה: In plain words: java.nio.file.NoSuchFileException: books.txt: אף אחד לא יצר את הקובץ.java.nio.file.NoSuchFileException: books.txt: nobody created the file.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

07הצעד של היום בפרויקט מדףToday's step in the Shelf project

Storage.save(List<Book>, Path) כותב שורה title;author;year לכל ספר, ו-Storage.load(Path) קורא בחזרה. שמרו, הדפיסו את הקובץ, טענו, והדפיסו 2 loaded, same: true (records משווים לפי תוכן).

Storage.save(List<Book>, Path) writes a title;author;year line per book, and Storage.load(Path) reads it back. Save, print the file, load, and print 2 loaded, same: true (records compare by content).

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich