Text files: write and read with Scanner · קבצי טקסט: כתיבה וקריאה עם Scanner
Reading and writing text files
- A text file stores text that stays on disk after the program ends.
- To read a file in Java we use a
Scannerconnected to aFile. - To write a file we use a
PrintWriter. In this lesson each program writes a file, then reads it back. - Bonus lesson: the AP CSA exam does not test file input/output. Learn this for real programs — you will not be examined on it.
קריאה וכתיבה בקבצי טקסט
- קובץ טקסט מאחסן טקסט שנשאר על דיסק לאחר שהתוכנית מסתיימת.
- כדי לקרוא קובץ ב-Java אנו משתמשים ב-
Scannerשמחובר ל-File. - כדי לכתוב קובץ אנו משתמשים ב-
PrintWriter. בשיעור זה כל תוכנית כותבת קובץ ולאחר מכן קוראת אותו חזרה. - שיעור נוסף: מבחן AP CSA אינו בודק כניסה/יציאה לקבצים. למד זאת לתוכניות אמיתיות — לא תבחן עליה.
Reading and writing a file · קריאה וכתיבה בקובץ
A file is used in three steps: open it, read or write lines, then close it. · קובץ משמש בשלושה שלבים: פתח אותו, קרא או כתוב שורות, ולאחר מכן סגור אותו.
The imports you need
- File tools live in two places, so we import both at the top.
import java.io.*;— forFile,PrintWriter, andIOException.import java.util.Scanner;— for theScannerreader.
הייבואים שאתה צריך
- כלי קובץ נמצאים בשני מקומות, לכן אנו יוראים את השניים בראש.
import java.io.*;— עבורFile,PrintWriterוIOException.import java.util.Scanner;— עבור הקוראScanner.
import java.io.*;
import java.util.Scanner;
Files can fail, so we say throws IOException
- Reading or writing a file can go wrong (the file may be missing).
- Java makes you handle this. The simplest way is to add
throws IOExceptiontomain. - This says "if a file error happens, let the program stop". That is fine for these tasks.
קבצים יכולים לכשל, ולכן אנחנו אומרים throws IOException
- קריאה או כתיבה בקובץ עשויה להיכשל (הקובץ עשוי להיות חסר).
- Java מחייבת אותך להתמודד עם זאת. הדרך הפשוטה ביותר היא להוסיף
throws IOExceptionלmain. - דבר זה אומר "אם מתרחשת שגיאת קובץ, תן לתוכנה להפסיק". זה בסדר למשימות אלו.
Writing a file with PrintWriter
new PrintWriter("data.txt")makes (or empties) a file calleddata.txt.- Use
writer.println(...)to write one line, just like printing to the screen. - Always call
writer.close()when you finish, so the text is saved.
כתיבת קובץ עם PrintWriter
new PrintWriter("data.txt")יוצר (או מנקה) קובץ הנקראdata.txt.- השתמש ב
writer.println(...)כדי לכתוב שורה אחת, בדיוק כמו הדפסה למסך. - תמיד קראו
writer.close()בסיום, כדי שהטקסט יישמר.
import java.io.*;
public class WriteDemo {
public static void main(String[] args) throws IOException {
PrintWriter writer = new PrintWriter("data.txt");
writer.println(10);
writer.println(20);
writer.close(); // save the file
System.out.println("wrote data.txt");
}
}
Reading numbers with Scanner
new Scanner(new File("data.txt"))opens the file for reading.in.hasNextInt()istruewhile there is another whole number to read.in.nextInt()reads the next whole number. Callin.close()when done.
קריאת מספרים באמצעות Scanner
new Scanner(new File("data.txt"))פותח את הקובץ לקריאה.in.hasNextInt()הואtrueכל עוד יש מספר שלם נוסף לקרוא.in.nextInt()קורא את המספר השלם הבא. קרא לin.close()כאשר סיימת.
import java.io.*;
import java.util.Scanner;
public class ReadNumbers {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("data.txt"));
int total = 0;
while (in.hasNextInt()) { // more numbers?
total = total + in.nextInt();
}
in.close();
System.out.println(total);
}
}
Reading whole lines
- Sometimes a line is text, not a number. Then read lines instead.
in.hasNextLine()istruewhile there is another line.in.nextLine()reads the whole next line as aString.
קריאת שורות שלמות
- לעיתים שורה היא טקסט ולא מספר. אז קרא שורות במקום זאת.
in.hasNextLine()הואtrueכל עוד יש שורה נוספת.in.nextLine()קורא את השורה הבאה כולה כString.
hasNext()(noIntorLine) checks for the next word, andnext()reads one word.- The pattern is always: check with a
hasNext...method, then read with the matching method.
import java.io.*;
import java.util.Scanner;
public class ReadLines {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("data.txt"));
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println("read: " + line);
}
in.close();
}
}
hasNext()(ללאIntאוLine) בודק את המילה הבאה, וnext()קורא מילה אחת.- הדפוס הוא תמיד: בדיקה עם שיטת
hasNext..., ולאחר מכן קריאה עם השיטה המתאימה.
Write then read in one program
- In each task your program first writes a file, then reads the same file back.
- This means you can run it again and again and get the same result.
כתיבה ולאחר מכן קריאה בתוכנית אחת
- בכל משימה התוכנית שלך תחילה כותבת קובץ, ואז קוראת את אותו קובץ בחזרה.
- משמעות הדבר היא שניתן להריץ אותה שוב ושוב ולקבל את התוצאה עצמה.
import java.io.*;
import java.util.Scanner;
public class RoundTrip {
public static void main(String[] args) throws IOException {
PrintWriter writer = new PrintWriter("data.txt");
writer.println(3);
writer.println(4);
writer.close();
Scanner in = new Scanner(new File("data.txt"));
int total = 0;
while (in.hasNextInt()) {
total = total + in.nextInt();
}
in.close();
System.out.println(total); // 7
}
}
Common mistakes
nextInt()leaves the newline, so a followingnextLine()reads an empty line.- Check
hasNext()before reading to avoid running off the end.
טעויות נפוצות
nextInt()משאיר את סימן הרווח החדש, לכןnextLine()הבא יקרא שורה ריקה.- בדוק
hasNext()לפני הקריאה כדי למנוע גלישה מעבר לקצה.
Now you try
- Each task pre-fills a class. Write the file first, then read it back, as the prompt asks.
- Remember the
throws IOExceptiononmain, andclose()both the writer and theScanner. - Press Run to compile and run, then Check answer.
כעת תנסו בעצמכם
- כל משימה ממלאה מראש מחלקה. כתוב את הקובץ תחילה, ואז קרא אותו בחזרה, כפי שהדרישה מבקשת.
- זכור את
throws IOExceptionבmain, וגם אתclose()של כותב הקובץ וגם של הScanner. - לחץ על Run כדי להרכיב ולהריץ, ולאחר מכן לחץ על Check answer.
First write the numbers 10, 20, 5, 7 to data.txt (one per line) with a PrintWriter. Then open it with new Scanner(new File("data.txt")) and use hasNextInt/nextInt to add them up. Print only the total. Expected output: 42. · ראשית, כתוב את המספרים 10, 20, 5, 7 ל-data.txt (אחד בכל שורה) עם PrintWriter. לאחר מכן פתח אותו עם new Scanner(new File("data.txt")) והשתמש ב-hasNextInt/nextInt כדי לחבר אותם יחד. הדפס רק את הסך הכולל. תוצאה צפויה: 42.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
First write the lines apple, banana, cherry to words.txt with a PrintWriter. Then open it with a Scanner and use hasNextLine/nextLine to count the lines. Print only the count. Expected output: 3. · ראשית, כתוב את השורות apple, banana, cherry ל-words.txt עם PrintWriter. לאחר מכן פתח אותו עם Scanner והשתמש ב-hasNextLine/nextLine לספור את השורות. הדפס רק את הספירה. תוצאה צפויה: 3.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.