נבנה על ידי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.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

פתקיםNotes

תזכורת: מה ביקשוReminder: the task

כתבו לקובץ notes.txt שלוש שורות (buy milk, call Noa, read Dune), קראו אותן בחזרה, והדפיסו 3 lines, 25 chars ואת השורה האחרונה.

Write three lines to notes.txt (buy milk, call Noa, read Dune), read them back, and print 3 lines, 25 chars and the last line.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
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("notes.txt");
        Files.write(p, List.of("buy milk", "call Noa", "read Dune"));
        List<String> lines = Files.readAllLines(p);
        int chars = 0;
        for (String l : lines) {
            chars += l.length();
        }
        System.out.println(lines.size() + " lines, " + chars + " chars");
        System.out.println(lines.get(lines.size() - 1));
    }
}
פלטOutput
3 lines, 25 chars
read Dune

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

יומן ביקוריםA visit log

תזכורת: מה ביקשוReminder: the task

לכל דף (home, shop, cart) הוסיפו לסוף visits.log שורה visit <page> (עם CREATE ו-APPEND), אחרי שמוחקים יומן ישן עם deleteIfExists. הדפיסו את הקובץ ואת מספר השורות (3).

For each page (home, shop, cart) append a line visit <page> to visits.log (with CREATE and APPEND), after deleting any old log with deleteIfExists. Print the file and the number of lines (3).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
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;

public class Main {
    public static void main(String[] args) throws IOException {
        Path log = Path.of("visits.log");
        Files.deleteIfExists(log);
        for (String page : List.of("home", "shop", "cart")) {
            Files.writeString(log, "visit " + page + "\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        }
        System.out.print(Files.readString(log));
        System.out.println(Files.readAllLines(log).size());
    }
}
פלטOutput
visit home
visit shop
visit cart
3

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

מ-CSV ל-recordsFrom CSV to records

תזכורת: מה ביקשוReminder: the task

כתבו books.csv עם שורת כותרת ושלושה ספרים, קראו, דלגו על הכותרת, והפכו כל שורה ל-record Book(title, author, year). הדפיסו 3 books, average year 1901 ואת הספר השני.

Write books.csv with a header line and three books, read it, skip the header, and turn each line into record Book(title, author, year). Print 3 books, average year 1901 and the second book.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        Path csv = Path.of("books.csv");
        Files.writeString(csv, "title,author,year\nEmma,Austen,1815\nDune,Herbert,1965\nUlysses,Joyce,1922\n");
        List<Book> books = new ArrayList<>();
        for (String line : Files.readAllLines(csv).subList(1, 4)) {
            String[] f = line.split(",");
            books.add(new Book(f[0], f[1], Integer.parseInt(f[2])));
        }
        double avg = books.stream().mapToInt(Book::year).average().orElse(0);
        System.out.println(books.size() + " books, average year " + Math.round(avg));
        System.out.println(books.get(1));
    }
}

record Book(String title, String author, int year) {
}
פלטOutput
3 books, average year 1901
Book[title=Dune, author=Herbert, year=1965]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

צייד באגים: קובץ חסרBug hunter: a missing file

תזכורת: מה ביקשוReminder: the task

התוכנית מהתזכורת קורסת. אם הקובץ לא קיים, צרו אותו עם Dune ו-Emma והדפיסו created a new books.txt. אחר כך 2 books.

The program from the refresher crashes. If the file doesn't exist, create it with Dune and Emma and print created a new books.txt. Then 2 books.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
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");
        if (!Files.exists(p)) {
            Files.write(p, List.of("Dune", "Emma"));
            System.out.println("created a new books.txt");
        }
        List<String> lines = Files.readAllLines(p);
        System.out.println(lines.size() + " books");
    }
}
פלטOutput
created a new books.txt
2 books

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

שמירה כ-JSONSaving as JSON

תזכורת: מה ביקשוReminder: the task

toJson(List<Book>) בונה מערך JSON עם StringJoiner. שמרו ל-shelf.json, קראו בחזרה והדפיסו: [{"title": "Dune", "rating": 5}, {"title": "Emma", "rating": 4}] ואז true 64.

toJson(List<Book>) builds a JSON array with a StringJoiner. Save to shelf.json, read it back and print: [{"title": "Dune", "rating": 5}, {"title": "Emma", "rating": 4}] then true 64.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.StringJoiner;

public class Main {
    static String toJson(List<Book> books) {
        StringJoiner arr = new StringJoiner(", ", "[", "]");
        for (Book b : books) {
            arr.add("{\"title\": \"" + b.title() + "\", \"rating\": " + b.rating() + "}");
        }
        return arr.toString();
    }

    public static void main(String[] args) throws IOException {
        Path p = Path.of("shelf.json");
        Files.writeString(p, toJson(List.of(new Book("Dune", 5), new Book("Emma", 4))));
        String back = Files.readString(p);
        System.out.println(back);
        System.out.println(back.startsWith("[") + " " + Files.size(p));
    }
}

record Book(String title, int rating) {
}
פלטOutput
[{"title": "Dune", "rating": 5}, {"title": "Emma", "rating": 4}]
true 64

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 6

מדף, צעד 29: שמירה וטעינהShelf, step 29: save and load

תזכורת: מה ביקשוReminder: the task

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).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("shelf.csv");
        List<Book> shelf = List.of(new Book("Dune", "Herbert", 1965), new Book("Emma", "Austen", 1815));
        Storage.save(shelf, file);
        System.out.print(Files.readString(file));
        List<Book> loaded = Storage.load(file);
        System.out.println(loaded.size() + " loaded, same: " + loaded.equals(shelf));
    }
}

record Book(String title, String author, int year) {
}

class Storage {
    static void save(List<Book> books, Path file) throws IOException {
        List<String> lines = new ArrayList<>();
        for (Book b : books) {
            lines.add(b.title() + ";" + b.author() + ";" + b.year());
        }
        Files.write(file, lines);
    }

    static List<Book> load(Path file) throws IOException {
        List<Book> out = new ArrayList<>();
        for (String line : Files.readAllLines(file)) {
            String[] f = line.split(";");
            out.add(new Book(f[0], f[1], Integer.parseInt(f[2])));
        }
        return out;
    }
}
פלטOutput
Dune;Herbert;1965
Emma;Austen;1815
2 loaded, same: true

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

לקרוא JSON פשוטReading simple JSON

תזכורת: מה ביקשוReminder: the task

parse(String json) מוציאה title ו-year מאובייקט JSON שטוח, בכל סדר ובכל ריווח, בעזרת Pattern ו-Matcher. הדפיסו Book[title=Dune, year=1965] ו-Book[title=Emma, year=1815]. (בפרויקט אמיתי: Jackson.)

parse(String json) pulls title and year out of a flat JSON object, in any order and spacing, using Pattern and Matcher. Print Book[title=Dune, year=1965] and Book[title=Emma, year=1815]. (In a real project: Jackson.)

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    static final Pattern FIELD = Pattern.compile("\"(\\w+)\"\\s*:\\s*(\"([^\"]*)\"|-?\\d+)");

    static Book parse(String json) {
        String title = null;
        int year = 0;
        Matcher m = FIELD.matcher(json);
        while (m.find()) {
            if (m.group(1).equals("title")) {
                title = m.group(3);
            } else if (m.group(1).equals("year")) {
                year = Integer.parseInt(m.group(2));
            }
        }
        return new Book(title, year);
    }

    public static void main(String[] args) {
        System.out.println(parse("{\"title\": \"Dune\", \"year\": 1965}"));
        System.out.println(parse("{\"year\":1815,\"title\":\"Emma\"}"));
    }
}

record Book(String title, int year) {
}
פלטOutput
Book[title=Dune, year=1965]
Book[title=Emma, year=1815]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

תיקיותFolders

תזכורת: מה ביקשוReminder: the task

צרו את library/scifi (עם createDirectories), כתבו בה שני קבצים, הדפיסו את שמותיהם ממוינים ([dune.txt, solaris.txt]), מחקו את dune.txt, והדפיסו false library/scifi.

Create library/scifi (with createDirectories), write two files in it, print their names sorted ([dune.txt, solaris.txt]), delete dune.txt, and print false library/scifi.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) throws IOException {
        Path dir = Path.of("library", "scifi");
        Files.createDirectories(dir);
        Files.writeString(dir.resolve("dune.txt"), "Herbert");
        Files.writeString(dir.resolve("solaris.txt"), "Lem");
        try (Stream<Path> files = Files.list(dir)) {
            System.out.println(files.map(f -> f.getFileName().toString()).sorted().toList());
        }
        Files.delete(dir.resolve("dune.txt"));
        System.out.println(Files.exists(dir.resolve("dune.txt")) + " " + dir);
    }
}
פלטOutput
[dune.txt, solaris.txt]
false library/scifi

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

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