Tải bản đầy đủ (.ppt) (88 trang)

Lập trình mạng 7 chuyên đề java io stream

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.07 MB, 88 trang )

Chapter 7
Input/Output Streams
1
Java Simplified / Session 22 / 2 of 45

Explain the concept of streams

Explain the standard input/output streams

Explain the ByteStream I/OStream

Explain the classes: FileInputStream and
FileOutputStream

Describe the Byte array I/O

Discuss Filtered and Buffered I/O operations
◦ Discuss the class RandomAccessFile, File

Explain the CharacterStream

Explain classes: Write, Reader, OutputStreamWriter,
InputStreamReader, FileWriter, FileReader.

Explain BufferedStream

Explain Serialization
Objectives
2
Java Simplified / Session 22 / 3 of 45


Stream là các dãy dữ liệu có sắp thứ tự

Truyền dữ liệu cho một chương trình Java:

Thông qua giao diện người máy.

Thông qua một tài nguyên tuần tự nào đó như file
hoặc qua một máy tính khác.

Java nhận và gửi dữ liệu thông qua các đối
tượng là các thực thể thuộc một kiểu luồng dữ
liệu nào đó.

Phân loại luồng thành hai loại:

Luồng xuất (output stream) và
◦ luồng nhập (input stream).
Streams
3
Java Simplified / Session 22 / 4 of 45
I/O Stream
4
Java Simplified / Session 22 / 5 of 45

An I/O Stream represents an input source or an
output destination.

A stream can represent many different kinds of
sources and destinations, including disk files,
devices, other programs, and memory arrays.


Streams support many different kinds of data,
including simple bytes, primitive data types,
localized characters, and objects.

Some streams simply pass on data; others
manipulate and transform the data in useful ways
I/O Stream
5
Java Simplified / Session 22 / 6 of 45
Stream
Console
Devices
File
Network
6
Java Simplified / Session 22 / 7 of 45

Khi 1 stream được đọc hoặc ghi thì các các
luồng khác sẽ bị khóa.

Ngoại lệ: trong khi đọc hoặc ghi 1 stream, nếu
xảy ra lỗi: IOException is thrown.

Dùng kết hợp với khối try/ catch block.
Streams Contd…
7
Java Simplified / Session 22 / 8 of 45

Standard input/output stream in Java is

represented by three fields of the System
class :

System.in,

System.out and

System.err.
Standard input/output stream
8
Java Simplified / Session 22 / 9 of 45
Example
class BasicIO {
public static void main(String args[])
{
byte bytearr[] = new byte[30];
try
{
System.out.println("Enter a line of text");
System.in.read(bytearr,0,30);
System.out.println("The line typed was ");
String str = new String(bytearr);
System.out.println(str);
} catch(Exception e)
{
System.out.println("Error occurred!");
}
}
}
9

Java Simplified / Session 22 / 10 of 45
There are two main categories of streams
in Java :

Byte Streams – Cung cấp cách thao tác
việc nhập/ xuất theo byte
InputStream and OutputStream classes are at
the top of their hierarchy.

Character Streams – Cung cấp cách thao
tác việc nhập/ xuất theo character.
The java.io package
10
Java Simplified / Session 22 / 11 of 45
Hierarchy of classes and interfaces
11
Object
File
FileDescriptor
RandomAccessFile
DataInput
DataOutput
DataInput
Stream
Buffered
InputStream
LineNumber
InputStream
PushBack
InputStream

Filter
InputStream
InputStream
ByteArray
InputStream
FileInput
Stream
OutputStream
FileOutput
Stream
Filter
OutputStream
ByteArray
OutputStream
Buffered
OutputStream
DataOutput
Stream
Print
Stream
Java Simplified / Session 22 / 12 of 45

Hai lớp trừu tượng làm cơ sở để xây dựng
các lớp con, có nhiệm vụ cung cấp cách thức
nhập xuất dữ liệu theo byte vào tệp:

InputStream class

File/ByteArray/Filter/ObjectInputStream


OutputStream class

File/ByteArray/Filter/ObjectOutputStream
Byte Streams
12
Java Simplified / Session 22 / 13 of 45
InputStream
FileInputStream
ByteArrayInputStream
FilterInputStream
ObjectInputStream

Xác định cách thức lấy
dữ liệu

Cung cấp cách đọc dữ
liệu từ 1 luồng nhập:
Định nghĩa các method
để đọc dữ liệu

Có các lớp con
InputStream class
13
Java Simplified / Session 22 / 14 of 45
OutputStream
FileOutputStream
ByteArrayOutputStream
FilterOutputStream
ObjectOutputStream


Xác định cách ghi dữ
liệu vào luồng output

Định nghĩa các
method để ghi dữ liệu

Các các class con
OutputStream class
14
Java Simplified / Session 22 / 15 of 45

Các phương thức của I/O Stream class

Các lớp con: (constructors, methods)

FileInputStream, FileOutputStream

ByteArrayInputStream, ByteArrayOutputStream

FilterInputStream, FilterOutputStream

BufferedInputStream, BufferedOutputStream
I/O Stream Class
15
Java Simplified / Session 22 / 16 of 45

Đọc từng byte từ tệp

int read() throws IOException
Return value (8 low bits of int): 0-255; end of stream: -1


int read(byte[] b) throws IOException
Read data from input stream to array b

int read(byte[] b, int offs, int len) throws
IOException
Read data from input stream to array b, start offs, save len bytes

public int available() throws IOException

Numbers data bytes left in Stream
Methods in InputStream class
16
Java Simplified / Session 22 / 17 of 45

public long skip(long count) throws IOException

Skip count data bytes

public synchronized void mark(int readLimit)

Mark current position in InputStream

public void reset() throws IOException

Redefine recent marked position in InputStream .

public boolean markSupported()

True: support mark, flase: not support


public void close() throws IOException

Close file. Release resource
Methods in InputStream class
17
Java Simplified / Session 22 / 18 of 45

Ghi từng byte vào tệp:

void write(int b) throws IOException
Write every byte to file (8 low bits of int).
b = 0-255; others, b=b mod 256

void write(byte[] b) throws IOException
Write bytes from output stream to array b

void write(byte[] b, int offs, int len)
throws IOException
Write bytes from output stream to array b, start offs,
save len bytes

void flush() Close file
Methods in OutputStream class
18
Java Simplified / Session 22 / 19 of 45

Dùng để đọc dữ liệu dưới dạng byte từ File
(String or Object) vào InputStream.


Constructors of this class :

FileInputStream(String filename)
throws FileNotFoundException
: Creates an InputStream that we can use to
read bytes from a filename (string).

FileInputStream(File filename)
throws FileNotFoundException
: Creates an input stream that we can use to read
bytes from a file where filename is a File
object.
FileInputStream class
19
Java Simplified / Session 22 / 20 of 45
Ex: Read and display data from file
20
import java.io.FileInputStream;
class BasicIO {
public static void main(String args[]) throws Exception {
FileInputStream fis = new FileInputStream("a.txt");
// Read and display data (int type)
int i;
while ((i = fis.read()) != -1) {
System.out.print(i + " ");
}
fis.close();
}
}
Java Simplified / Session 22 / 21 of 45


Tạo 1 luồng FileInputStream.

Đọc file và In ra màn hình dạng ký tự: 2 cách

Đọc byte từ file vào mảng, tạo String từ mảng byte

Đọc từng byte ra dạng char (ép kiểu)

Đóng file
Thực hiện đọc dữ liệu từ File
21
Java Simplified / Session 22 / 22 of 45
Example
import java.io.*;
class FileDemo {
public static void main(String args[]) throws
Exception {
int size;
InputStream f = new FileInputStream("a.txt");
System.out.println("Bytes available to read : " +
(size = f.available()));
byte[] buff = new byte[500];
f.read(buff,10,size);
String s = new String(buff);
System.out.print(s);
f.close();
}
}
while (f.available() > 0) {

char ch = (char) f.read();
System.out.print(ch);
}
22
Java Simplified / Session 22 / 23 of 45

Dùng để viết dữ liệu dạng byte từ OutputStream
vào file.

Its constructors are :

FileOutputStream(String filename) throws
FileNotFoundException : Creates an OutputStream
that we can use to write bytes to a file.

FileOutputStream(File name) throws
FileNotFoundException : Creates an OutputStream
that we can use to write bytes to a file.

FileOutputStream(String filename, boolean
flag) throws FileNotFoundException : Creates
an OutputStream that we can use to write bytes to a file.
If flag is true, file is opened in append mode.
FileOutputStream class
23
Java Simplified / Session 22 / 24 of 45

Nhập dữ liệu

Khai báo 1 mảng byte để nhận dữ liệu nhập

vào

Tạo 1 luồng FileOutputStream (filename)

Ghi dữ liệu từ OutputStream vào file
Thực hiện ghi byte dữ liệu vào File
24
Java Simplified / Session 22 / 25 of 45
Example
class FileOutputDemo {
public static void main(String args[]) {
byte b[] = new byte[80];
try {
System.out.println("line to be saved into file");
int bytes = System.in.read(b);
FileOutputStream fos = new
FileOutputStream("a.txt");
fos.write(b,0,bytes);
System.out.println("Written!");
} catch(IOException e) {
System.out.println("Error creating file!"); }
}
}
25
String s="cong hoa xa hoi VN";
byte b[] = s.getBytes();
try {
FileOutputStream fos = new FileOutputStream("aa.txt");
fos.write(b,0,b.length);

×