Cơ bản về xử lý I/O trong Java

Sau khi tìm hiểu, bạn sẽ thấy rằng gói java.io cung cấp nhiều lớp và abstract class để làm việc với dữ liệu đầu vào/đầu ra. Có thể phân loại các luồng (stream) theo ba tiêu chí chính:

  • Hướng dữ liệu: InputStream (đọc vào) và OutputStream (ghi ra) — luôn xét từ góc độ chương trình.
  • Đơn vị xử lý: Byte stream (xử lý byte) và Character stream (xử lý ký tự Unicode).
  • Chức năng: Node stream (trực tiếp đọc/ghi file) và Filter stream (xử lý bổ sung trên dữ liệu).

1. Đọc file bằng byte stream

import java.io.*;

public class DocFileTheoByte {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("duong_dan_file.jsp")) {
            int data;
            long count = 0;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
                count++;
            }
            System.out.println("\nĐã đọc: " + count + " byte");
        } catch (FileNotFoundException e) {
            System.err.println("Không tìm thấy file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. Đọc file bằng character stream

import java.io.*;

public class DocFileTheoKyTu {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("duong_dan_file.jsp")) {
            int ch;
            long count = 0;
            while ((ch = reader.read()) != -1) {
                System.out.print((char) ch);
                count++;
            }
            System.out.println("\nĐã đọc: " + count + " ký tự");
        } catch (FileNotFoundException e) {
            System.err.println("Không tìm thấy file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. Ghi file bằng byte stream (sao chép file)

import java.io.*;

public class SaoChepFileByte {
    public static void main(String[] args) {
        try (
            FileInputStream in = new FileInputStream("source.avi");
            FileOutputStream out = new FileOutputStream("target.avi")
        ) {
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            System.out.println("Sao chép hoàn tất.");
        } catch (IOException e) {
            System.err.println("Lỗi sao chép file.");
        }
    }
}

4. Ghi file bằng character stream

import java.io.*;

public class GhiFileKyTu {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("output.txt")) {
            for (int i = 33; i <= 126; i++) { // ghi các ký tự ASCII in được
                writer.write(i);
            }
            System.out.println("Ghi file thành công.");
        } catch (IOException e) {
            System.err.println("Lỗi ghi file.");
        }
    }
}

5. Sao chép video hoặc file nhị phân

import java.io.*;

public class CopyBinaryFile {
    public static void main(String[] args) {
        try (
            FileInputStream source = new FileInputStream("video_goc.mp4");
            FileOutputStream dest = new FileOutputStream("video_moi.mp4")
        ) {
            byte[] buffer = new byte[8192]; // dùng buffer để tăng hiệu suất
            int bytesRead;
            while ((bytesRead = source.read(buffer)) != -1) {
                dest.write(buffer, 0, bytesRead);
            }
            System.out.println("Hoàn tất sao chép file nhị phân.");
        } catch (IOException e) {
            System.err.println("Lỗi trong quá trình sao chép.");
        }
    }
}

Thẻ: Java io FileInputStream FileOutputStream FileReader

Đăng vào ngày 24 tháng 7 lúc 14:53