การอ่านและเขียนไฟล์

Input/Output และ Streams ใน Java

Alex Liu

Software Development Engineer

การ Casting

  • การแปลงระหว่างประเภทข้อมูลพื้นฐาน

  • Widening casting - แปลงอัตโนมัติจากขนาดเล็กไปใหญ่

    • byte -> short -> char -> int -> long -> float -> double
// Widening casting - happens automatically
byte myByte = 8;
int myInt = myByte;
  • Narrowing casting - แปลงแบบ manual จากขนาดใหญ่ไปเล็ก
// Narrowing casting - is manual
double myDouble = 3.14;
int myInt = (int) myDouble; // Note the (int)
Input/Output และ Streams ใน Java

ทำความเข้าใจการ Casting สำหรับการอ่านไฟล์

  • การ cast จาก int เป็น char: char data = (char) 123;
// Unicode value for character 'a'
int data = 97;
// Directly print the data in `int` format
System.out.print(data);
// Cast data from `int` to `char` and print
System.out.print((char)data);
97
a
1 https://www.ascii-code.com/
Input/Output และ Streams ใน Java

การอ่านข้อมูลจากไฟล์ด้วย FileReader

  • นำเข้าคลาส FileReader เพื่อเปิดใช้งานฟังก์ชันอ่านไฟล์
import java.io.FileReader;
  • อ่านไฟล์ แสดงผลทีละอักขระ แล้วปิดไฟล์
FileReader fr = new FileReader("example.txt");
int data = fr.read();
// Read and print each character
while (data != -1) {
    System.out.print((char) data);
    data = fr.read();
}
fr.close(); // Close the file to release resources
Input/Output และ Streams ใน Java

การอ่านที่มีประสิทธิภาพด้วย BufferedReader

  • BufferedReader - import java.io.BufferedReader;
    • อ่านไฟล์ข้อความทีละบรรทัด
    • มีประสิทธิภาพสูงกว่าสำหรับไฟล์ขนาดใหญ่
// Create a BufferedReader object
BufferedReader br = new BufferedReader(new FileReader("example.txt"));
String line;
// User .readLine() to read the file line by line
while ((line = br.readLine())!= null){
  System.out.println(line);
}
br.close();
Input/Output และ Streams ใน Java

การเขียนข้อมูลด้วย FileWriter

  • FileWriter:
    • เขียนทับเนื้อหาเดิมโดยค่าเริ่มต้น — ระวังข้อมูลสูญหาย!
  • นำเข้า FileWriter
import java.io.FileWriter;


// Create a new `FileWriter` Object FileWriter fw = new FileWriter("example.txt"); // Write the data to file using `.write() fw.write("Overwriting the file."); fw.close()
Input/Output และ Streams ใน Java

การต่อท้ายข้อมูลด้วย FileWriter

  • FileWriter
    • รองรับการต่อท้ายข้อมูลโดยตั้งค่าเป็นโหมด append โดยไม่เขียนทับเนื้อหาเดิม

$$

// Initialize `FileWriter` with append mode
FileWriter fw = new FileWriter("example.txt", true);
// Append data to the file
fw.write("Appending data.");
fw.close()
Input/Output และ Streams ใน Java

การเขียนที่มีประสิทธิภาพด้วย BufferedWriter

  • BufferedWriter - import java.io.BufferedWriter;
    • เขียนข้อความได้มีประสิทธิภาพกว่าด้วยการประมวลผลเป็นกลุ่มใหญ่
    • ลดจำนวนครั้งในการเขียนข้อมูล
// Create a BufferedWriter object
BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt"));
bw.write("Writing data");

// .newLine() to add line breaks
bw.newLine(); 
bw.close();
Input/Output และ Streams ใน Java

มาฝึกกันเถอะ!

Input/Output และ Streams ใน Java

Preparing Video For Download...