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และIOExceptionimport 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 เพื่อ compile และ 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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่