נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
קבצים עם NIO ו-JSONFiles with NIO & JSON
מפגש 29: Path ו-Files, קריאה וכתיבה של טקסט, CSV, ושמירה וטעינה של JSON.Session 29: Path and Files, reading and writing text, CSV, and saving and loading JSON.
Path ו-Files, קריאה וכתיבה של טקסט, CSV, ושמירה וטעינה של JSON. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Path and Files, reading and writing text, CSV, and saving and loading JSON. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- לכתוב ולקרוא קובץWriting and reading a file
- להוסיף לסוף, ולקרוא כזרםAppending, and reading as a stream
- JSON בידJSON by hand
- קובץ שלא קייםA file that doesn't exist
- טעויות נפוצותCommon mistakes
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגשThis session's terms
- Path: כתובת של קובץ או תיקייה:Path: The address of a file or folder:
- Files: מחלקת עזר עם כל הפעולות:Files: A utility class with all the operations:
- CSV: קובץ טקסט שבו כל שורה היא רשומה ושדות מופרדים בפסיק (או
;).CSV: A text file where each line is a record and fields are separated by a comma (or ;). - JSON: פורמט טקסט לנתונים:JSON: A text format for data:
- NoSuchFileException: החריגה כשקוראים קובץ שלא קיים.NoSuchFileException: The exception when reading a file that doesn't exist.
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושאTopic 2
לכתוב ולקרוא קובץWriting and reading a file
לכתוב ולקרוא קובץWriting and reading a file
- Files עושה את כל העבודה:
writeString יוצר את הקובץ, readAllLines מחזיר רשימת שורות.Files does all the work: writeString creates the file, readAllLines returns a list of lines. main מכריז throws IOException, כי פעולות על קבצים יכולות להיכשל.main declares throws IOException, because file operations can fail.
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.נושאTopic 3
להוסיף לסוף, ולקרוא כזרםAppending, and reading as a stream
להוסיף לסוף, ולקרוא כזרםAppending, and reading as a stream
StandardOpenOption.APPEND מוסיף לסוף במקום לדרוס.StandardOpenOption.APPEND adds to the end instead of overwriting.Files.lines מחזיר Stream של שורות שמחזיק את הקובץ פתוח, ולכן הוא ב-try-with-resources.Files.lines returns a Stream of lines that keeps the file open, so it goes in a try-with-resources.
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.נושאTopic 4
JSON בידJSON by hand
JSON בידJSON by hand
- JSON הוא רק טקסט עם כללים: מחרוזות במירכאות, ומירכאות בתוך מחרוזת צריך לסמן ב-
\".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.
- במחשב שלכם, Jackson עושה את זה בשורה:
new ObjectMapper().writeValueAsString(book).On your computer, Jackson does it in one line: new ObjectMapper().writeValueAsString(book).
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).נושאTopic 5
קובץ שלא קייםA file that doesn't exist
נושאTopic 6
טעויות נפוצותCommon mistakes
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
- `java.nio.file.NoSuchFileException:`java.nio.file.NoSuchFileException:
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.נושאTopic 7
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 29: שמירה וטעינהShelf, step 29: save and load
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).Path: כתובת של קובץ או תיקייה:Path: The address of a file or folder:
המונחים של המפגשThis session's termsFiles: מחלקת עזר עם כל הפעולות:Files: A utility class with all the operations:
המונחים של המפגשThis session's termsCSV: קובץ טקסט שבו כל שורה היא רשומה ושדות מופרדים בפסיק (או ;).CSV: A text file where each line is a record and fields are separated by a comma (or ;).
המונחים של המפגשThis session's termsJSON: פורמט טקסט לנתונים:JSON: A text format for data:
המונחים של המפגשThis session's termsNoSuchFileException: החריגה כשקוראים קובץ שלא קיים.NoSuchFileException: The exception when reading a file that doesn't exist.
המונחים של המפגשThis session's termsFiles עושה את כל העבודה: writeString יוצר את הקובץ, readAllLines מחזיר רשימת שורות.Files does all the work: writeString creates the file, readAllLines returns a list of lines.
לכתוב ולקרוא קובץWriting and reading a filemain מכריז throws IOException, כי פעולות על קבצים יכולות להיכשל.main declares throws IOException, because file operations can fail.
לכתוב ולקרוא קובץWriting and reading a fileStandardOpenOption.APPEND מוסיף לסוף במקום לדרוס.StandardOpenOption.APPEND adds to the end instead of overwriting.
להוסיף לסוף, ולקרוא כזרםAppending, and reading as a streamFiles.lines מחזיר Stream של שורות שמחזיק את הקובץ פתוח, ולכן הוא ב-try-with-resources.Files.lines returns a Stream of lines that keeps the file open, so it goes in a try-with-resources.
להוסיף לסוף, ולקרוא כזרםAppending, and reading as a streamJSON הוא רק טקסט עם כללים: מחרוזות במירכאות, ומירכאות בתוך מחרוזת צריך לסמן ב-\".JSON is just text with rules: strings in quotes, and quotes inside a string must be escaped as \".
JSON בידJSON by handכאן כותבים אותו ביד כדי להבין את המבנה.Here we write it by hand to understand the shape.
JSON בידJSON by handבמחשב שלכם, Jackson עושה את זה בשורה: new ObjectMapper().writeValueAsString(book).On your computer, Jackson does it in one line: new ObjectMapper().writeValueAsString(book).
JSON בידJSON by handקובץ שלא קייםA file that doesn't exist`java.nio.file.NoSuchFileException:`java.nio.file.NoSuchFileException:
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java saysמדף, צעד 29: שמירה וטעינהShelf, step 29: save and load
הצעד של היום בפרויקט מדףToday's step in the Shelf projectמה עושה Files.writeString(p, "x") כשהקובץ כבר קיים?What does Files.writeString(p, "x") do when the file already exists?
- דורס אותוOverwrites it
- מוסיף לסוףAppends
- זורק חריגהThrows
- לא עושה כלוםDoes nothing
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.דורס אותוOverwrites it
נכון. להוספה לסוף: StandardOpenOption.APPEND.Right. To add to the end: StandardOpenOption.APPEND.למה Files.lines(p) צריך try-with-resources?Why does Files.lines(p) need try-with-resources?
- כי ה-Stream מחזיק את הקובץ פתוח עד שסוגרים אותוBecause the Stream keeps the file open until it's closed
- כי הוא איטיBecause it's slow
- כי javac מחייבBecause javac requires it
- לא צריךIt doesn't
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.כי ה-Stream מחזיק את הקובץ פתוח עד שסוגרים אותוBecause the Stream keeps the file open until it's closed
נכון.Right.IOException היא...IOException is...
- checkedchecked
- uncheckedunchecked
- לא חריגהNot an exception
- שגיאת קומפילציהA compile error
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.checkedchecked
נכון: חובה לטפל או להכריז.Right: you must handle or declare it.פתקיםNotes
- כתבו לקובץ
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 exercise from the practice page: ask how you would start.יומן ביקוריםA visit log
- לכל דף (
home, shop, cart) הוסיפו לסוף visits.log שורה visit <page> (עם CREATE ו-APPEND), אחרי שמוחקים יומן ישן עם deleteIfExists.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.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מ-CSV ל-recordsFrom CSV to records
- כתבו
books.csv עם שורת כותרת ושלושה ספרים, קראו, דלגו על הכותרת, והפכו כל שורה ל-record Book(title, author, year).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).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: קובץ חסרBug hunter: a missing file
- התוכנית מהתזכורת קורסת.The program from the refresher crashes.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.שמירה כ-JSONSaving as JSON
toJson(List<Book>) בונה מערך JSON עם StringJoiner.toJson(List<Book>) builds a JSON array with a StringJoiner.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 29: שמירה וטעינהShelf, step 29: save and load
Storage.save(List<Book>, Path) כותב שורה title;author;year לכל ספר, ו-Storage.load(Path) קורא בחזרה.Storage.save(List<Book>, Path) writes a title;author;year line per book, and Storage.load(Path) reads it back.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.לקרוא JSON פשוטReading simple JSON
parse(String json) מוציאה title ו-year מאובייקט JSON שטוח, בכל סדר ובכל ריווח, בעזרת Pattern ו-Matcher.parse(String json) pulls title and year out of a flat JSON object, in any order and spacing, using Pattern and Matcher.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מה למדנוWhat we learned
- Path: כתובת של קובץ או תיקייה:Path: The address of a file or folder:
- Files עושה את כל העבודה:
writeString יוצר את הקובץ, readAllLines מחזיר רשימת שורות.Files does all the work: writeString creates the file, readAllLines returns a list of lines. StandardOpenOption.APPEND מוסיף לסוף במקום לדרוס.StandardOpenOption.APPEND adds to the end instead of overwriting.- JSON הוא רק טקסט עם כללים: מחרוזות במירכאות, ומירכאות בתוך מחרוזת צריך לסמן ב-
\".JSON is just text with rules: strings in quotes, and quotes inside a string must be escaped as \". - קוראים קובץ שאף אחד לא יצר, ומקבלים NoSuchFileException.Reading a file nobody created gives a NoSuchFileException.
- `java.nio.file.NoSuchFileException:`java.nio.file.NoSuchFileException:
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.