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

חזרה למפגשBack
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.

מה נעשה היום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
נושאTopic 1

מונחיםTerms

המונחים של המפגש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.
נושא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.
נושא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.
נושא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).
נושאTopic 5

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

קובץ שלא קיים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:
נושאTopic 7

פרויקט מדףShelf project

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

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

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.

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.

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.

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

קוראים קובץ שאף אחד לא יצר, ומקבלים NoSuchFileException.Reading a file nobody created gives a NoSuchFileException.

`java.nio.file.NoSuchFileException:`java.nio.file.NoSuchFileException:

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

מה עושה Files.writeString(p, "x") כשהקובץ כבר קיים?What does Files.writeString(p, "x") do when the file already exists?

  • דורס אותוOverwrites it
  • מוסיף לסוףAppends
  • זורק חריגהThrows
  • לא עושה כלוםDoes nothing

דורס אותוOverwrites it

למה 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

כי ה-Stream מחזיק את הקובץ פתוח עד שסוגרים אותוBecause the Stream keeps the file open until it's closed

IOException היא...IOException is...

  • checkedchecked
  • uncheckedunchecked
  • לא חריגהNot an exception
  • שגיאת קומפילציהA compile error

checkedchecked

פתקים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.

יומן ביקורים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.

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

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

  • התוכנית מהתזכורת קורסת.The program from the refresher crashes.

שמירה כ-JSONSaving as JSON

  • toJson(List<Book>) בונה מערך JSON עם StringJoiner.toJson(List<Book>) builds a JSON array with a StringJoiner.

מדף, צעד 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.

לקרוא 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.

מה למדנו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:

עכשיו לתרגולNow, practice

6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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