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.
Trang 1Chapter 7
Input/Output Streams
1
Trang 2Java 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
Trang 3Java 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:
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:
Streams
3
Trang 4Java Simplified / Session 22 / 4 of 45
I/O Stream
4
Trang 5Java 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
Trang 6Java Simplified / Session 22 / 6 of 45
Stream
Console
Devices File
Network
6
Trang 7Java 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
Trang 8Java Simplified / Session 22 / 8 of 45
Standard input/output stream in Java is represented by three fields of the System class :
Trang 9Java 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.out.println("The line typed was ");
String str = new String(bytearr);
System.out println(str);
} catch(Exception e)
{ System.out println("Error occurred!");
} }
}
9
Trang 10Java 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
Trang 11Java Simplified / Session 22 / 11 of 45
Hierarchy of classes and interfaces
11
Object File FileDescriptor
RandomAccessFile
DataInput Stream InputStreamBuffered InputStreamLineNumber InputStreamPushBack
Filter InputStream
InputStream
ByteArray InputStream
FileInput Stream
OutputStream
FileOutput Stream
Filter OutputStream OutputStreamByteArray
Buffered OutputStream
DataOutput Stream Print
Stream
Trang 12Java 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:
Trang 13Java Simplified / Session 22 / 13 of 45
Trang 14Java Simplified / Session 22 / 14 of 45
Định nghĩa các method để ghi dữ liệu
Các các class con
OutputStream class
14
Trang 15Java 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)
Trang 16Java Simplified / Session 22 / 16 of 45
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
Trang 17Java 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
Trang 18Java 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
Trang 19Java 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 :
Trang 20Java 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();
}}
Trang 21Java 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
Trang 22Java Simplified / Session 22 / 22 of 45
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();
} }
char ch = ( char ) f.read();
System out print(ch);
} 22
Trang 23Java Simplified / Session 22 / 23 of 45
vào file.
◦ 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
Trang 24Java 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
Trang 25Java 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!"); } }
Trang 26Java Simplified / Session 22 / 26 of 45
Ex:Copy a file with read(byte[] data) and write(byte[] data)
FileInputStream fin = null;
FileOutputStream fout = null;
File file = new File("C:/myfile1.txt");
fin = new FileInputStream(file);
fout = new FileOutputStream("C:/myfile2.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fin.read(buffer)) > 0) { fout.write(buffer, 0, bytesRead);
} fin.close();
fout.close();
}}
26
Trang 27Java Simplified / Session 22 / 27 of 45
Dùng 1 mảng byte như là nguồn dữ liệu vào (not file)
Methods : read(), skip(), available(), reset() (from parent class)
Its constructors are :
Trang 28Java Simplified / Session 22 / 28 of 45
Khai báo 1 mảng byte (hoặc String), nhận dữ liệu
Tạo một luồng nhập mảng byte từ mảng byte (hoặc String)
Đọc dữ liệu từ luồng nhập mảng byte (String)
Trang 29Java Simplified / Session 22 / 29 of 45
Ex: Convert string into InputStream using ByteArrayInputStream class
import java.io.*;
class ByteDemo { public static void main (String []args) { String str = "Độc lập tự do hạnh phúc Việt Nam";
byte[] b = str.getBytes();
InputStream bais = new ByteArrayInputStream(b,0,0);
int ch;
while((ch = bais.read()) != -1) System.out.print((char) ch);//ep kieu System.out.println();
bais.reset(); //using reset ( ) method and again reading
ch = 0;
while((ch = bais.read()) != -1) System.out.print((char) ch);
} }
29
Trang 30Java Simplified / Session 22 / 30 of 45
Tạo ra một luồng xuất trên 1 mảng byte.
two constructors.
◦ ByteArrayOutputStream(int size) used to set the output byte array to an initial size.
◦ ByteArrayOutputStream() sets the output buffer to a default size
Additional methods like:
◦ String toByteArray() and
Trang 31Java Simplified / Session 22 / 31 of 45
Khai báo 1 mảng byte, nhận dữ liệu cần ghi
Tạo một luồng xuất mảng byte
Ghi dữ liệu từ mảng byte vào luồng xuất mảng byte
Có thể in ra màn hình (chuyển luồng sang string)
Cách thức ghi dữ liệu vào luồng mảng byte
31
Trang 32Java Simplified / Session 22 / 32 of 45
Ex: Convert OutputStream to String using ByteArrayOutputStream class
import java.io.*;
class ByteOutDemo {public static void main (String []args) throws IOException {String str = "Jack and Jill went up the hill";
Trang 33Java Simplified / Session 22 / 33 of 45
Ex ByteArrayIOStream
33
public class ByteArrayIOApp {
public static void main(String args[]) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
String s = "This is a test." ; for (int i = 0; i < s.length(); ++i)
outStream.write(s.charAt(i));
System.out println( "outstream: " + outStream);
System.out println( "size: " + outStream.size());
ByteArrayInputStream inStream;
inStream = new ByteArrayInputStream(outStream.toByteArray());
int inBytes = inStream.available();
System.out println( "inStream has" + inBytes + "available bytes" );
byte inBuf[] = new byte[inBytes];
int bytesRead = inStream.read(inBuf, 0, inBytes);
System.out println(bytesRead + " bytes were read" );
System.out println( "They are: " + new String(inBuf));
} }
Trang 34Java Simplified / Session 22 / 34 of 45
luồng thô
dữ liệu thô với chúng nhằm mục đích chuyển đổi qua lại giữa các byte và các khuôn dạng dữ liệu khác
xử lý dữ liệu
và luồng ghi (writer)
Filter Streams
34
Trang 35Java Simplified / Session 22 / 35 of 45
Là lớp cơ sở của all các lớp làm nhiệm vụ như bộ lọc của các luồng input/output
Các lớp con:
DataOutputStream.
◦ FilterInputStream: lớp cơ sở của luồng nhập
protected FilterInputStream(InputStream in)
◦ FilterOutputStream: lớp cơ sở của luồng xuất
public FilterOutputStream(OutputStream out)
Filter Input and Output classes
35
Trang 36Java Simplified / Session 22 / 36 of 45
trình đọc/ghi sẽ nhanh hơn
liệu tạm khi đọc/ghi dữ liệu
từng buffer byte:
chương trình và đích của luồng buffer
Buffered I/O classes
36
Trang 37Java Simplified / Session 22 / 37 of 45
Lớp BufferedInputStream :
◦ Có một mảng byte được sử dụng để làm vùng đệm
◦ Khi gọi đọc luồng read(), trước tiên nó nhận dữ liệu được yêu cầu từ vùng đệm (Khi vùng đệm hết dữ liệu thực sự
nó mới đọc dữ liệu từ nguồn)
◦ đọc càng nhiều dữ liệu từ nguồn vào vùng đệm
two constructors:
◦ BufferedInputStream(InputStream is): Creates
a buffered input stream for the specified InputStream instance.
◦ BufferedInputStream(InputStream is, int
size): Creates a buffered input stream of a given size
for the specified InputStream instance.
BufferedInputStream
37
Trang 38Java Simplified / Session 22 / 38 of 45
Ex Read from String with BufferedInputStream
38
System out println( "Enter a line:" );
System out print(( char )x + " " );}
} }
}
Trang 39Java Simplified / Session 22 / 39 of 45
For faster reading you should use BufferedInputStream to wrap any InputStream
Trang 40Java Simplified / Session 22 / 40 of 45
Ex, Read from file with BufferedInputStream
40
Exception {
byte [] buffer = new byte [1024];
BufferedInputStream bi = new BufferedInputStream( new
FileInputStream( "b.txt" ));
int bytesRead = 0;
{
String chunk = new String(buffer, 0, bytesRead);
System out print(chunk);
} bi.close();
} }
Trang 41Java Simplified / Session 22 / 41 of 45
Lớp BufferedOutputStream :
vùng đệm đầy hoặc là luồng bị flush()
two constructors:
buffered output stream for the specified OutputStream instance with a buffer size of 512.
the specified OutputStream instance.
BufferedOutputStream
41
Trang 42Java Simplified / Session 22 / 42 of 45
Example: Buffered Stream Copier
42
public class BuffOutput {
public static void main(String[] args) throws IOException {
FileInputStream fi= new FileInputStream( "a.txt" );
FileOutputStream fo= new FileOutputStream( "b.txt" );
try {
copy(fi, fo);
} catch (IOException ex) { System.err println(ex); }
} public static void copy(FileInputStream in, FileOutputStream out) throws IOException {
BufferedInputStream bin = new BufferedInputStream(in);
BufferedOutputStream bout = new BufferedOutputStream(out);
}}
Trang 43Java Simplified / Session 22 / 43 of 45
File class cung cấp giao diện chung để làm việc trực tiếp hệ thống tệp
Các phương thức cho phép tạo, xóa, đổi tên cho file và thư mục
File class is used whenever there is a need to work with files and directories on the file system.
File class
43
Trang 44Java Simplified / Session 22 / 44 of 45
1.public File(String pathname)
2.public String getName()
3.public boolean exists()
4.public long length()
5.public long lastModified()
6.public boolean canRead()
7.public boolean canWrite()
8.public boolean isFile()
9.public boolean isDirectory()
10.public String[] list()
11.public boolean mkdir()
12. boolean renameTo(File dest)
13. public boolean delete()
File class: Constructor and Methods
44
Trang 45Java Simplified / Session 22 / 45 of 45
class FileInfo { static void show(String s) {
System.out println(s);
File f1 = new File(fi);
show(f1.getName()+(f1.exists()? " exists" : " does not exist" ));
show ( "File size :" +f1.length()+ " bytes" );
show ( "Is" +(f1.isDirectory()? " a directory" : "not a directory" ));
show (f1.getName()+(f1.canWrite()? " is writable" : " is not writable" ));
show(f1.getName()+(f1.canRead()? " is readable" : " is not readable" ));
show( "File was last modified :" + f1.lastModified());
} }
Example
45
Trang 46Java Simplified / Session 22 / 46 of 45
Ex: Creates a file and sets it to read-only
46
public class CreateFile_RO {
public static void main (String[] args) throws IOException
{
// Create a new file, by default canWrite=true,
boolean readonly= false ;
File file = new File ( "test.txt" );
if (file exists ())
file.delete ();
file.createNewFile ();
System.out println ( "Before canWrite? " + file canWrite ());
// set to read-only, atau canWrite = false */
file.setWritable (false );
System.out println ( "After canWrite? " + file canWrite ());
}}