Danh mục tài liệu

Lập trình Java cơ bản : Luồng và xử lý file part 3

Số trang: 5      Loại file: pdf      Dung lượng: 66.09 KB      Lượt xem: 15      Lượt tải: 0    
Xem trước 2 trang đầu tiên của tài liệu này:

Thông tin tài liệu:

Các luồng file• Được sử dụng để xuất nhập với file. • Luồng nhập từ file: FileInputStream• FileInputStream(String name) • FileInputStream(File f)• Luồng xuất ra file: FileOutputStream• FileOutputStream(String name) • FileOutputStream(File f) • FileOutputStream(String name, boolean append)
Nội dung trích xuất từ tài liệu:
Lập trình Java cơ bản : Luồng và xử lý file part 3Các luồng file• Được sử dụng để xuất nhập với file.• Luồng nhập từ file: FileInputStream • FileInputStream(String name) • FileInputStream(File f)• Luồng xuất ra file: FileOutputStream • FileOutputStream(String name) • FileOutputStream(File f) • FileOutputStream(String name, boolean append)• Phương thức nhập/xuất của các luồng file giống như của các luồng nhập xuất cơ bản 11Ví dụ: Đọc và hiển thị file (v1)import java.io.*;public class ReadFile{ public static void main(String[] args) { try { FileInputStream f = new FileInputStream(readme.txt); int ch; while ( (ch = f.read()) != -1 ) { System.out.print((char)ch); } f.close(); } catch (FileNotFoundException d) { System.out.println(File not found); } catch (IOException d) { System.out.println(Can not read file); } } 12}Ví dụ: Ghi dữ liệu ra fileimport java.io.*;public class WriteFile{ public static void main(String[] args) { byte buffer[] = new byte[80]; try { System.out.println(Enter a string to write to file: ); int num = System.in.read(buffer); FileOutputStream f = new FileOutputStream(line.txt); f.write(buffer, 0, num); f.close(); } catch (IOException e) { System.out.println(Error IO file); } }} 13Luồng lọc (filter stream)• Luồng lọc có khả năng kết nối với các luồng khác và xử lý dữ liệu “theo cách riêng” của nó.• FilterInputStream và FilterOutputStream là 2 lớp luồng lọc cơ bản. Filter Stream Input Stream Input Device 14Luồng nhập/xuất dữ liệu sơ cấp• DataInputStream và DataOutputStream là 2 lớp lọc cho phép nhập xuất dữ liệu thuộc các kiểu sơ cấp. DataInputStream Input Stream char Input long Device float ... 15