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

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • Path: כתובת של קובץ או תיקייה:Path: The address of a file or folder:
  • Files: מחלקת עזר עם כל הפעולות:Files: A utility class with all the operations:
  • 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.
  • קוראים קובץ שאף אחד לא יצר, ומקבלים NoSuchFileException.Reading a file nobody created gives a NoSuchFileException.

מונחיםTerms

  • PathPath: כתובת של קובץ או תיקייה: Path.of("library", "scifi"). נתיב יחסי מתחיל מהתיקייה שבה התוכנית רצה.The address of a file or folder: Path.of("library", "scifi"). A relative path starts from the folder the program runs in.
  • FilesFiles: מחלקת עזר עם כל הפעולות: writeString, readString, write, readAllLines, lines, exists, size, createDirectories, list, delete. רובן זורקות IOException (checked).A utility class with all the operations: writeString, readString, write, readAllLines, lines, exists, size, createDirectories, list, delete. Most throw IOException (checked).
  • CSVCSV: קובץ טקסט שבו כל שורה היא רשומה ושדות מופרדים בפסיק (או ;). פשוט, אבל צריך להיזהר מפסיק בתוך שדה.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.
  • JSONJSON: פורמט טקסט לנתונים: {"title": "Dune", "year": 1965}, ומערכים ב-[...]. בפרויקט אמיתי משתמשים ב-Jackson או Gson, שממירים record ל-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.
  • NoSuchFileExceptionNoSuchFileException: החריגה כשקוראים קובץ שלא קיים. היא IOException, כלומר checked.The exception when reading a file that doesn't exist. It's an IOException, so it's checked.
  • PathPath: כתובת של קובץ או תיקייה: Path.of("library", "scifi"). נתיב יחסי מתחיל מהתיקייה שבה התוכנית רצה.The address of a file or folder: Path.of("library", "scifi"). A relative path starts from the folder the program runs in.
  • FilesFiles: מחלקת עזר עם כל הפעולות: writeString, readString, write, readAllLines, lines, exists, size, createDirectories, list, delete. רובן זורקות IOException (checked).A utility class with all the operations: writeString, readString, write, readAllLines, lines, exists, size, createDirectories, list, delete. Most throw IOException (checked).
  • CSVCSV: קובץ טקסט שבו כל שורה היא רשומה ושדות מופרדים בפסיק (או ;). פשוט, אבל צריך להיזהר מפסיק בתוך שדה.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.
  • JSONJSON: פורמט טקסט לנתונים: {"title": "Dune", "year": 1965}, ומערכים ב-[...]. בפרויקט אמיתי משתמשים ב-Jackson או Gson, שממירים record ל-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.
  • NoSuchFileExceptionNoSuchFileException: החריגה כשקוראים קובץ שלא קיים. היא IOException, כלומר checked.The exception when reading a file that doesn't exist. It's an IOException, so it's checked.

Cheatsheet

לכתוב ולקרוא קובץWriting and reading a file
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");
להוסיף לסוף, ולקרוא כזרםAppending, and reading as a stream
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));
JSON בידJSON by hand
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"));

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
NoSuchFileExceptionקובץ שלא קייםA file that doesn't existjava.nio.file.NoSuchFileException: books.txt: בודקים קודם עם Files.exists, או תופסים את החריגה.java.nio.file.NoSuchFileException: books.txt: check first with Files.exists, or catch the exception.
NoSuchFileExceptionצייד באגים: קובץ חסרBug hunter: a missing filejava.nio.file.NoSuchFileException: books.txt: אף אחד לא יצר את הקובץ.java.nio.file.NoSuchFileException: books.txt: nobody created the file.

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