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. - اضغط تشغيل للمعالجة والتشغيل، ثم تحقق من الإجابة.
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. · اضغط تشغيل لرؤية المخرجات هنا.