שימוש בקבצי טקסט
הוצג
13:31
אוספי נתונים
קחו תמונה אחת בטלפון שלכם. למחשב זו לא תמונה בכלל — זו רשת של מספרים, אחד לכל פיקסל, כעשרה מיליון מהם. עכשיו נסו…
קריינות באנגלית · כתוביות באנגלית ובסינית 中文 שאפשר להחליף ביניהן
בשיעור הזה
| English | משמעות |
|---|---|
| text file/tekst faɪl/ | קובץ טקסט |
A blank line is not an invalid token
- A text file 文本文件 contains a blank line followed by
12. At the start, bothhasNextLine()andhasNextInt()are true: the integer-token check skips whitespace, including the blank line, to find 12. - Compare a file containing
oopsfollowed by12: it has another line, but its next token is not an integer. A line-presence check cannot establish integer format; choose a guard that matches the read.


עם המפריד הברירת מחדל, Scanner המכיל שורה ריקה שלאחריה 12 מדווח hasNextInt() כ-true בהתחלה.
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
בדיקת טוקן של מספר שלם דורשת רווחים, כולל השורה הריקה, ומצאת את טוקן המספר 12.
Attach the reader to its source
new Scanner(new File("scores.txt"))reads the named file, whereasnew Scanner(System.in)reads keyboard input. Both expose the same Scanner methods; the source and its availability differ.- Opening a missing file can throw
FileNotFoundException. The complete example below declares it onmain; a real application could instead catch it and report a useful error. Neither choice creates missing data.
כדי לקרוא קובץ טקסט, מחברים Scanner ל-...
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
new Scanner(new File("...")) קורא קובץ.
אותן שיטות Scanner (nextInt, nextLine) עובדות גם לקלט מהמקלדת וגם לקלט מקובץ.
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
ההבדל היחיד הוא במקור (System.in לעומת File).
Read complete lines
hasNextLine()checks whether another line exists without consuming it;nextLine()consumes the remainder of that line and its line separator. A blank line can produce the empty string"".- For line-based records, use
while (in.hasNextLine()) { String line = in.nextLine(); ... }. Decide explicitly whether an empty record is meaningful, should be skipped, or should be reported as invalid.
קריאת קובץ טקסט
עקבו אחרי השלבים שבהם תוכנית קוראה קובץ שורה אחר שורה.
איזו שיטה בודקת אם קיים עוד שורה לקריאה?
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
hasNextLine() משמש כמגן לקריאה של nextLine().
חובה לבדוק את hasNextLine() לפני כל קריאה ל-nextLine().
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
ניסיון לקרוא מעבר לסוף הקובץ גורם לפליטת חריגה.
Read tokens with matching checks
- Scanner's default delimiter is whitespace.
hasNext()checks for a token;next()consumes it.hasNextInt()checks whether the next token can be read as an integer;nextInt()consumes that integer. while (in.hasNextInt())stops atoops, even if 12 follows. If the policy is to skip invalid tokens and retain later integers, loop withhasNext(), testhasNextInt(), and consume an invalid token withnext().
This complete program sums valid integer tokens and reports every skipped token. For a file containing oops followed by 12, it prints Skipped: oops and then Total: 12. The example assumes the sum fits in an int.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadScores {
public static void main(String[] args) throws FileNotFoundException {
int total = 0;
try (Scanner in = new Scanner(new File("scores.txt"))) {
while (in.hasNext()) {
if (in.hasNextInt()) {
total += in.nextInt();
} else {
System.out.println("Skipped: " + in.next());
}
}
}
System.out.println("Total: " + total);
}
}
Match each read to the guard that checks that kind of input.
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
A line-presence check is not an integer-format check.
Consume input and release the file
- Every branch in the token loop consumes a token. Repeatedly checking an invalid token without consuming it leaves the Scanner at the same position and can make a loop run forever.
- The try-with-resources block closes this file Scanner on exit, including exceptional exit. When managing it manually, call
close()when finished; checks do not replace closing the resource.
hasNextLine() followed by nextInt() is not a matching guard. A non-integer token can cause InputMismatchException, and that failed integer read leaves the token available. Choose whether to reject the file, report the record, or explicitly skip the token.
כשנגמרים לקרוא קובץ, עליך...
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
in.close() משחרר את הקובץ.
Check the data policy before the loop
- For input
8 oops 12, a loop that reads only whilehasNextInt()totals 8 and stops atoops. The shown skip-and-report policy totals 20. An unexpected token need not mean the file has ended. - These policies answer different questions. For a required score per student, silently skipping a bad token could misalign records; prefer reporting and rejecting that record rather than treating all later tokens as interchangeable scores.
Choose line or token reading from the file format. Checks inspect upcoming input without consuming it; matching reads consume it. Handle invalid data explicitly, advance every loop branch, and close the file reader.
לקלט 8 oops 12, מה הסכום שהתוכנית המוצגת מדפיסה?
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
היא צורכת והוסיפה 8, צרכה ודיווחה oops, ואז צרכה והוסיפה 12. הסכום הוא 20.
מה השתבש? רק צוות האתר רואה זאת.