Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

การเปลี่ยนทาง System.out.println() ไปยังไฟล์ใน Java

ฟิลด์ out ของคลาส System เป็น standard output stream (PrintStream) โดยค่าเริ่มต้นคือ console (หน้าจอ) เมธอด setOut(PrintStream) ใช้เปลี่ยน standard output stream ใหม่

ขั้นตอน

  1. สร้างออบเจ็กต์ File สำหรับไฟล์ปลายทาง
  2. สร้าง PrintStream โดยส่ง File object เข้าไป
  3. เรียก System.setOut(printStream)
  4. ทุก System.out.println() ต่อจากนี้จะเขียนไปไฟล์แทน

ตัวอย่างโค้ด


import java.io.File;
import java.io.IOException;
import java.io.PrintStream;

public class SetOutExample {
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\sample.txt");
        PrintStream stream = new PrintStream(file);
        
        System.out.println("From now on " + file.getAbsolutePath() + " will be your console");
        System.setOut(stream);
        
        // ตั้งแต่บรรทัดนี้ไป ทุกอย่างจะเขียนไปไฟล์
        System.out.println("Hello, how are you");
        System.out.println("Welcome to Tutorialspoint");
    }
}

ผลลัพธ์บน Console (ก่อน setOut)


From now on D:\sample.txt will be your console

เนื้อหาในไฟล์ sample.txt (หลัง setOut)


Hello, how are you
Welcome to Tutorialspoint

ข้อควรระวังและ Best Practices

1. ปิด Stream เมื่อใช้เสร็จ


PrintStream stream = new PrintStream(file);
try {
    System.setOut(stream);
    // ... print things ...
} finally {
    stream.close(); // สำคัญ: flush buffer และปล่อย file handle
}

2. ใช้ try-with-resources (Java 7+)


try (PrintStream stream = new PrintStream(new File("output.txt"))) {
    System.setOut(stream);
    System.out.println("This goes to file");
}
// stream ปิดอัตโนมัติ

3. เก็บ reference ของ System.out เดิมไว้ (เพื่อ restore)


PrintStream originalOut = System.out;
try (PrintStream fileOut = new PrintStream("log.txt")) {
    System.setOut(fileOut);
    System.out.println("Logged to file");
} finally {
    System.setOut(originalOut); // กลับมา console
    System.out.println("Back to console");
}

4. รองรับ UTF-8


PrintStream stream = new PrintStream(file, "UTF-8");

การใช้งานจริง: Logging Framework

สำหรับ production ควรใช้ logging framework เช่น SLF4J + Logback หรือ Log4j2 แทนการ redirect System.out โดยตรง เพราะมี:

  • Log levels (DEBUG, INFO, WARN, ERROR)
  • Rolling file appender (แบ่งไฟล์ตามวันที่/ขนาด)
  • Async logging (ไม่บล็อก thread หลัก)
  • Structured logging (JSON format)