View
1.522
Download
3
Category
Preview:
Citation preview
Chapter 7Input/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 Streams◦ Discuss the class RandomAccessFile, File
Explain the CharacterStream◦ Explain classes: Write, Reader, OutputStreamWriter,
InputStreamReader, FileWriter, FileReader. Explain Serialization
Objectives
2
Java Simplified / Session 22 / 3 of 45
A stream is a continuous group of data or a channel through which data travels from one point to another.
Two kinds streams:◦Input stream receives data from a source into a
program.◦Output stream sends data to a destination from
the program.
Streams
3
Java Simplified / Session 22 / 4 of 45
I/O Stream, ex
4
Java Simplified / Session 22 / 5 of 45
An I/O Stream represents an input source or an output destination.
Many different kinds of sources and destinations
Stream: many sources & destinations
5
Console
Devices
File
Network - simple bytes, - primitive data types, - localized characters, - and objects
Java Simplified / Session 22 / 6 of 45
When a stream is read/written, others threads are blocked.
Exception: while reading/writing in stream, errors may be occurs. IOException is thrown.◦public static void main(String args[]) throws IOException
◦ Using try/ catch block:try {
copy(fi, fo); } catch (IOException ex)
{ System.err.println(ex); }
Stream - exception
6
Java Simplified / Session 22 / 7 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
7
Java Simplified / Session 22 / 8 of 45
Exampleclass SimpleIO {public static void main(String args[]) {
byte bytearr[] = new byte[30];try { System.out.println("Enter a line: "); // Reads up to len bytes of data from
the //input stream into an array of bytesSystem.in.read(bytearr,0,30);
System.out.print("The line typed was: "); String str = new String(bytearr);//->str System.out.println(str); } catch(Exception e) { System.err.print("Error occurred:“ + e);
} }} 8
Java Simplified / Session 22 / 9 of 45
There are two main categories of streams in Java : Byte Streams – Provide input/output method in byteInputStream and OutputStream classes are at the top of their hierarchy. Character Streams – Provide input/output method in character.
The java.io package
9
Java Simplified / Session 22 / 10 of 45
Hierarchy of classes and interfaces
10
ObjectFile FileDescriptor
RandomAccessFileDataInput DataOutput
DataInputStream
BufferedInputStream
LineNumberInputStream
PushBackInputStream
FilterInputStrea
m
InputStream
ByteArrayInputStream
FileInputStream
OutputStream
FileOutputStream
FilterOutputStream
ByteArrayOutputStream
BufferedOutputStream
DataOutputStream
PrintStream
Java Simplified / Session 22 / 11 of 45
DataInput Interface
It is used to read bytes from a binary stream and reconstruct data in any of the java primitive types.
Allows us to convert data that is in Java modified Unicode Transmission Format (UTF-8) to string form.
DataInput interface defines a number of methods including methods for reading Java primitive data types.
Java Simplified / Session 22 / 12 of 45
DataOutput Interface
Used to reconstruct data that is in any of the Java primitive types into a series of bytes and writes them onto a binary system.
Allows us to convert a String into Java modified UTF-8 format and write it into a stream.
All methods under DataOutput interface throw an IOException in case of an error.
Java Simplified / Session 22 / 13 of 45
Two abstract are basic classes. They provide input/output methods in byte to file:◦InputStream class File/ByteArray/Filter/ObjectInputStream◦OutputStream class File/ByteArray/Filter/ObjectOutputStream
Byte Streams
13
Java Simplified / Session 22 / 14 of 45
Defines how data is received.
The basic purpose: read data from an input stream.
Defines methods to read data
Many subclasses:
Inpu
tStre
am
FileInputStream
ByteArrayInputStream
FilterInputStream
ObjectInputStream
InputStream class
14
Java Simplified / Session 22 / 15 of 45
Defines the way in which outputs are written to streams.
Used to write data to a stream.
Defines methods to write data.
Many subclasses:O
utpu
tStre
am
FileOutputStream
ByteArrayOutputStream
FilterOutputStream
ObjectOutputStream
OutputStream class
15
Java Simplified / Session 22 / 16 of 45
Methods of I/O Stream class:◦Support sub classes
Sub Classes: (constructors, methods)◦FileInputStream, FileOutputStream◦ByteArrayInputStream, ByteArrayOutputStream◦FilterInputStream, FilterOutputStream BufferedInputStream, BufferedOutputStream
I/O Stream Class
16
Java Simplified / Session 22 / 17 of 45
Read every byte from file (in byte)◦int read() Return value (8 low bits of int): 0-255; end of stream: -1◦int read(byte[] b) Read data from input stream to array b◦int read(byte[] b, int offs, int len) Read data from input stream to array b, start offs, save len bytes
public int available()◦Numbers data bytes left in Stream
Exception: throws IOException
Methods in InputStream class
17
Java Simplified / Session 22 / 18 of 45
public long skip(long count) ◦Skip count data bytes
public void reset() ◦Redefine recent marked position in InputStream .
public void close() ◦Close file. Release resource
Exception: throws IOException public synchronized void mark(int readLimit) ◦Mark current position in InputStream
public boolean markSupported() ◦True: support mark, flase: not support
Methods in InputStream class
18
Java Simplified / Session 22 / 19 of 45
Write every byte to file:◦void write(int b) Write every byte to file (8 low bits of int). b = 0-255; others, b=b mod 256◦void write(byte[] b) Write bytes from output stream to array b◦void write(byte[] b, int offs, int l)Write bytes from output stream to array b, start offs, save len bytes
Exception: throws IOException◦void flush() Close file
Methods in OutputStream class
19
Java Simplified / Session 22 / 20 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):
Creates an InputStream that we can use to read bytes from a filename (string).
◦FileInputStream(File filename): Creates an input stream that we can use to read bytes from a file where filename is a File object.
Exception: FileNotFoundException
FileInputStream class
20
Java Simplified / Session 22 / 21 of 45
Ex: Read and display data from file
21
import java.io.FileInputStream;class Read_Disp_File { 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 / 22 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 byteString s = new String(array);
◦Đọc từng byte ra dạng char (ép kiểu) (ko TV)char ch = (char) f.read();
Đóng file
Thực hiện đọc dữ liệu từ File
22
Java Simplified / Session 22 / 23 of 45
Example: read from fileimport java.io.*;class FileDemo { public static void main(String args[]) throws
Exception {InputStream f = new FileInputStream("a.txt");int size= f.available();System.out.println("Bytes available: " + size);byte[] buff = new byte[size];f.read(buff,0,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);}
23
Java Simplified / Session 22 / 24 of 45
Viết dữ liệu dạng byte từ OutputStream vào file. Its constructors are:
◦FileOutputStream(String filename) : Creates an OutputStream, to write bytes to a file.◦FileOutputStream(File name) : Creates an OutputStream, to write bytes to a file.◦FileOutputStream(String filename, boolean flag) :
Creates an OutputStream, to write bytes to a file. If flag is true, file is opened in append mode.Exception: FileNotFoundException
FileOutputStream class
24
Java Simplified / Session 22 / 25 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
25
Java Simplified / Session 22 / 26 of 45
Example: write data (bytes) to fileimport java.io.*;class FileOutputDemo {public static void main(String args[]) {String s="cộng hòa xã hội VN abcd";byte b[] = s.getBytes();try {FileOutputStream fos = new FileOutputStream("aa.txt"); fos.write(b,0,b.length); System.out.println(b.length + " bytes are written!");} catch(IOException e) { System.out.println("Error creating file!");
} }} 26
Java Simplified / Session 22 / 27 of 45
Ex:Copy a file with read(byte[] data) and write(byte[] data)public class CopyFileTV_ex { public static void main(String[] args) throws IOException { FileInputStream fin = null; FileOutputStream fout = null; // File fil = new File("a1.txt"); fin = new FileInputStream("a1.txt");//or: (fil) fout = new FileOutputStream("xyz.txt"); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fin.read(buffer)) > 0) { fout.write(buffer, 0, bytesRead); } fin.close(); fout.close(); }
27
int size = 0;try {size = SFile.available();byte[] b = new byte[size];SFile.read(b,0,size);DFile.write(b,0,size);} catch (IOException e) {// TODO e.printStackTrace();
}
Java Simplified / Session 22 / 28 of 45
Dùng 1 mảng byte như là nguồn dữ liệu vào (not file)
Methods : read(), skip(), reset(), available(), (from parent class)
Its constructors are :◦ByteArrayInputStream(byte b[]): Creates a ByteArrayInputStream with b as the input source.◦ByteArrayInputStream(byte b[]), int start, int num):
Creates a ByteArrayInputStream that begins with the character at start position and is num bytes long.
ByteArrayInputStream class
28
Java Simplified / Session 22 / 29 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) Có thể in ra màn hình
String text = "Converting String to InputStream Example";InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
Cách thức đọc dữ liệu từ luồng mảng byte
29
Java Simplified / Session 22 / 30 of 45
Ex: Convert string into InputStream using ByteArrayInputStream classimport 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,b.length);int ch;while((ch = bais.read()) != -1)
System.out.print((char) ch);//ep kieuSystem.out.println();bais.reset(); //using reset ( ) method and
again readingch = 0;while((ch = bais.read()) != -1)
System.out.print((char) ch);}
}
30
Java Simplified / Session 22 / 31 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 ◦String toString()
convert the stream to a byte array and String object respectively.
◦size(): size of buffer
ByteArrayOutputStream
31
Java Simplified / Session 22 / 32 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
32
Java Simplified / Session 22 / 33 of 45
Ex: Convert OutputStream to String using ByteArrayOutputStream classimport java.io.*;class ByteOutDemo {public static void main (String []args) throws IOException {
String str = "Jack and Jill went up the hill";byte[] b = str.getBytes();ByteArrayOutputStream b1 = new ByteArrayOutputStream();b1.write(b);System.out.println("Writing the contents of a ByteArrayOutputStream");System.out.println(b1.toString());}}
33
Java Simplified / Session 22 / 34 of 45
Ex ByteArrayIOStream
34
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)); }}
Java Simplified / Session 22 / 35 of 45
Các luồng InputStream và OuptutStream là các luồng thô.
Java cung cấp một số lớp lọc để ta gắn các luồng 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.
Filter Streams có thể kết nối với các Stream khác và xử lý dữ liệu
Các luồng lọc cũng có hai loại là:luồng đọc (reader) và luồng ghi (writer).
Filter Streams
35
Java Simplified / Session 22 / 36 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:◦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)◦BufferedInputStream
/BufferedOutputStream.
Filter Input and Output classes
36
Java Simplified / Session 22 / 37 of 45
Một buffer là khu vực lưu trữ tạm dữ liệu. Bằng cách lưu trữ dữ liệu trong buffer, quá
trình đọc/ghi sẽ nhanh hơn Java dùng buffered I/O để làm bộ lưu trữ dữ
liệu tạm khi đọc/ghi dữ liệu Hai lớp được sử dụng đọc/ghi dữ liệu theo
từng buffer byte: ◦BufferedInputStream◦BufferedOutputStream
Việc lọc trên buffer sẽ được tiến hành giữa chương trình và đích của luồng buffer.
Buffered I/O classes
37
Java Simplified / Session 22 / 38 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
38
Java Simplified / Session 22 / 39 of 45
Ex Read from String with BufferedInputStream
39
import java.io.BufferedInputStream;public class BuffInput {public static void main(String[] args) {System.out.println("Enter a line:");BufferedInputStream bi = new BufferedInputStream(System.in);try {for (int i=0; i<=bi.available(); i++ ){
int x = bi.read();System.out.print((char)x + " ");}} catch (Exception e)
{ e.printStackTrace();}
}}
Java Simplified / Session 22 / 40 of 45
For faster reading you should use BufferedInputStream to wrap any InputStreamEx, FileInputStream fis = new FileInputStream(aFile);BufferedInputStream bis = new BufferedInputStream (fis);
BufferedInputStream
40
Java Simplified / Session 22 / 41 of 45
Ex, Read from file with BufferedInputStream
41
public class BuffInput {public static void main(String[] args) throws Exception { byte[] buffer = new byte[1024]; BufferedInputStream bi = new BufferedInputStream(new
FileInputStream("b.txt")); int bytesRead = 0;
while ((bytesRead = bi.read(buffer)) != -1){
String chunk = new String(buffer, 0, bytesRead); System.out.print(chunk);
} bi.close(); }}
Java Simplified / Session 22 / 42 of 45
Lớp BufferedOutputStream :◦ lưu trữ dữ liệu được ghi vào trong một vùng đệm cho tới khi
vùng đệm đầy hoặc là luồng bị flush(). ◦ Sau đó nó ghi dữ tất cả dữ liệu ra luồng xuất đúng một lần. ◦ Điều này làm tăng tốc độ trao đổi dữ liệu
two constructors:◦BufferedOutputStream(OutputStream os): Creates a
buffered output stream for the specified OutputStream instance with a buffer size of 512.
◦BufferedOutputStream(OutputStream os, int size): Creates a buffered output stream of a given size for the specified OutputStream instance.
BufferedOutputStream
42
Java Simplified / Session 22 / 43 of 45
Example: Buffered Stream Copier
43
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); while (true) { int datum = bin.read(); if (datum == -1) break; bout.write(datum); } bout.flush(); }}
Java Simplified / Session 22 / 44 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
44
Java Simplified / Session 22 / 45 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
45
Java Simplified / Session 22 / 46 of 45
class FileInfo {static void show(String s) {System.out.println(s);
}public static void main(String args[]){String fi;Scanner in= new Scanner(System.in);fi=in.next();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
46
Java Simplified / Session 22 / 47 of 45
Ex: Creates a file and sets it to read-only
47
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, canWrite = false */ file.setWritable (false); System.out.println ("After. canWrite? " + file.canWrite ()); }}
Java Simplified / Session 22 / 48 of 45
public static void main(String[] args) {JFileChooser dialogF;dialogF=new JFileChooser();dialogF.setDialogTitle("Select File to Open");dialogF.showOpenDialog(dialogF);//dialogF.showSaveDialog(dialogF); }
Ex,TrivialEdit.java
Files in GUI Programs
48
Java Simplified / Session 22 / 49 of 45
It supports reading/writing of all primitive types. RandomAccessFile cho phép ta truy nhập trực tiếp vào các tệp,
nghĩa là có thể đọc, ghi các byte ở bất kỳ vị trí nào đó trong tệp. (ex, readByte, writeByte…)
Các phương thức tạo luồng truy nhập tệp ngẫu nhiên ◦ RandomAccessFile(String name, String mode) throws IOException
◦ RandomAccessFile(File file, String mode) throws IOException
mode: “r”, “rw” or “rws” as a parameter for read only, read/write and read/write with every change.◦ long getFilePointer() throws IOException : positon of pointer◦ long length() throws IOException: length of file ◦ void seek(long offset) throws IOException: move pointer to
offset◦ void close() throws IOException: close file.
RandomAccessFile
49
Java Simplified / Session 22 / 50 of 45
Ex, Write, modify and read file (byte)import java.io.IOException;import java.io.RandomAccessFile;
public class RAF_SaveRead { public static void main(String[] args) throws IOException { RandomAccessFile rf = new RandomAccessFile("test.dat", "rw"); for (int i = 0; i < 10; i++) rf.writeByte(i ); rf.close(); rf = new RandomAccessFile("test.dat", "rw"); rf.seek(5); //seek at the byte 5th rf.writeByte(100); //change value to 100 rf.close(); rf = new RandomAccessFile("test.dat", "r"); for (int i = 0; i < 10; i++) System.out.println("Value " + i + ": " + rf.readByte()); rf.close(); }}
50
Java Simplified / Session 22 / 51 of 45
Gói Java.io cung cấp 2 giao diện để cài đặt các hàm đọc/ghi dạng nhị phân của các giá trị nguyên thủy (boolean, char, int..)◦DataInput, DataOutput DataInputStream DataOutputStream
Phải được xây dựng như là một vỏ bọc cho đối tượng byte Stream
Các hàm đọc bắt đầu bằng read, hàm ghi bắt đầu bằng write. ◦Ex. readByte, writeInt
Đọc ghi dữ liệu nguyên thủy
51
Java Simplified / Session 22 / 52 of 45
Để đọc dạng nhị phân của các giá trị nguyen thủy từ tệp, thực hiện :◦Tạo 1 đối tượng FileInputStream: ex
FileInputStream inFile= new FileInputStream(““);◦Tạo 1 đối tượng DataInputStream (shell), ex
DataInputStream inStream=new DataInputStream(inFile);
◦Đọc các giá trị nguyên thủyChar c=inStream.readChar();Byte b=inStream.readByte();o Close file:inStream.close();
Đọc các giá trị nguyên thủy
52
Java Simplified / Session 22 / 53 of 45
Ghi dạng nhị phân của các giá trị nguyên thủy lên tệp, thực hiện:◦Tạo 1 đối tượng FileOutputStream: ex,
FileOutputStream outFile= new FileOutputStream(“ “);
◦Tạo 1 đối tượng DataOutputStreamDataOutputStream outStream=new DataOutputStream(outFile);
◦Ghi các giá trị nguyên thủyoutStream.writeChar(‘A’);//write ‘A’ outStream.writeByte(Byte.MAX_VALUE);o Close file:outStream.close();
Ghi các giá trị nguyên thủy
53
Java Simplified / Session 22 / 54 of 45
Ex, DataInput/OutputStream
54
public class DataIOStream { public static void main(String[] args) throws Exception{ int idA = 1234; String nameA = "Lê Văn Tèo"; FileOutputStream fos = new FileOutputStream("cities.txt"); DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(idA); dos.writeUTF(nameA); dos.close();
FileInputStream fis = new FileInputStream("cities.txt"); DataInputStream dis = new DataInputStream(fis);
int Id = dis.readInt(); System.out.println("Id: " + Id); String Name = dis.readUTF(); System.out.println("Name: " + Name); }}
Java Simplified / Session 22 / 55 of 45
Luồng ký tự cung cấp một cách thức để quản lý việc vào ra với các ký tự.
Các luồng này sử dụng tập ký tự Unicode và vì thế có thể quốc tế hóa.
Trong một số trường hợp làm việc với các luồng ký tự hiệu quả hơn luồng byte.
Các luồng kí tự chuẩn vay mượn từ rất nhiều các lớp luồng hướng byte: filter, buffer, file, sub of reader & write
Character streams
55
Java Simplified / Session 22 / 56 of 45
Hai lớp trừu tượng là cơ sở cho các lớp con nhằm làm cầu nối giữa các luồng byte và các luồng ký tự:◦Reader and◦Writer
Character streams
56
Java Simplified / Session 22 / 57 of 4557
FileWriter
Java Simplified / Session 22 / 58 of 45
Xác định cách mã hóa được sử dụng bởi các luồng byte:◦Các ký tự được biểu diễn bởi từng byte hoặc từng
nhóm các byte. ◦Tên của cách mã hóa các byte được đặc tả bởi
một xâu ký tự được truyền cho constructor tạo cầu nối OuputStreamReader và InputStreamReader.
◦Ex, UTF-8 (16,16LB), US-ASCII, IBM-EBCDIC(Universal Character Set Transformation Format—8-bit)
Get the default encoding of your computerSystem.out.println(System.getProperty("file.encoding"));
Mã hóa ký tự
58
Java Simplified / Session 22 / 59 of 45
Used for reading character streams and is abstract. Constructor:
◦ protected Reader(), protected Reader(Object lock) Some of the methods used are :
Reader class
Method Purposeabstract void close() throws IOException
Closes the stream
int read() throws IOException Reads one characterint read(char buf[]) throws IOException
Reads characters into an array
void reset() throws IOException Resets the streamlong skip(long n) throws IOException
Skips n characters
boolean ready() throws IOException
Determines if the stream is ready to be run 59
Java Simplified / Session 22 / 60 of 45
An abstract class , supports writing into streams Constructor:
◦ protected Writer(), protected Writer(Object obj) Some of the methods used are :
Writer class
Method Purposeabstract void close() throws IOException
Closes the stream
abstract void flush( ) throws IOException
Flushes the stream
void write(char[] c) throws IOException
Writes the specified array of characters
abstract void write(char [] c, int offset, int n) throws IOException
Writes the specified length of characters from offset position in the array
60
Java Simplified / Session 22 / 61 of 45
Cung cấp một cầu nối Writer hướng ký tự với một luồng OutputStream.
Các ký tự được ghi vào lớp Writer được chuyển thành các byte tương ứng với một kiểu mã hóa được xác định trong constructor và sau đó được ghi vào luồng OutputStream gắn với nó.
Constructors:◦ public OutputStreamWriter(OutputStream out) ◦ public OutputStreamWriter(OutputStream out, String encoding)
◦ String getEncoding() Phương thức này trả về tên cách mã hóa các byte được sử dụng để chuyển đổi các ký tự thành các byte.
OutputStreamWriter class
61
Java Simplified / Session 22 / 62 of 45
Ex, write char to file (BasicIO.java)
62
char[] chars = new char[2];chars[0] = '\u4F60';chars[1] = '\u597D';String encoding = "GB18030";File textFile = new File("a1.txt");OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream(textFile), encoding);wr.write(chars);
Java Simplified / Session 22 / 63 of 45
Lớp này biểu diễn một cầu nối hướng ký tự của một luồng nhập InputStream.
Các byte được đọc từ luồng nhập và được chuyển thành các ký tự tương ứng với kiểu mã hóa được xác định trong constructor
Constructor:◦InputStreamReader(InputStream in) ◦InputStreamReader(InputStream in, String enc) ◦String getEncoding(): tên cách mã hóa To create an InputStreamReader:
InputStreamReader reader = new InputStreamReader(new FileInputStream
(filePath), charSet);
InputStreamReader class
63
Java Simplified / Session 22 / 64 of 45
Ex: Write char to file and read char form file. BasicIO.java
Read char from file
64
String encoding = "GB18030";InputStreamReader reader = new InputStreamReader(new FileInputStream("a1.txt"), encoding); char[] chars2 = new char[2]; reader.read(chars2); System.out.println(chars2[0]); System.out.print(chars2[1]); reader.close();
Java Simplified / Session 22 / 65 of 45
Ex, UTF-8 coding
65
public class ReadWrite_UTF {public static void main(String[] args) { try { String st=“Cộng hòa xã hội chuI nghĩa VN";
OutputStreamWriter wri = new OutputStreamWriter( new FileOutputStream("b.txt"), "UTF-8"); char[] chars1 = st.toCharArray(); wri.write(chars1); //write wri.close();InputStreamReader rea = new InputStreamReader( new FileInputStream("b.txt"), "UTF-8"); char[] chars2 = new char[50]; rea.read(chars2); // read for (int i=0; i< chars2.length; i++) System.out.print(chars2[i]); } catch (IOException e) { System.out.println(e.toString()); } }}
Java Simplified / Session 22 / 66 of 45
FileWriter provides a convenient way of writing characters to a file.
FileWriter uses your computer's default character encoding
Constructor:public FileWriter (File file)public FileWriter (File file, boolean append)public FileWriter (String path)public FileWriter (String path, boolean append)public FileWriter (FileDescriptor fileDescriptor)
FileWriter Class
66
Java Simplified / Session 22 / 67 of 45
FileWriter Class
67
public class Read_Write_ex { public static void main(String[] argv) throws Exception { FileWriter fw = new FileWriter("aa.txt"); String strs[] = { "Công", "Nghệ", "Thông", "Tin" }; for (int i = 0; i < strs.length; i++) { fw.write(strs[i] + "\n"); } fw.close(); }}
Java Simplified / Session 22 / 68 of 45
The FileReader class is a subclass of InputStreamReader
The FileReader class is a convenient class to read characters from a file (using encoding).
The FileReader class uses an encoding other than the default one.
Constructor:public FileReader (File file)public FileReader (FileDescriptor fileDescriptor)public FileReader (String filePath)
FileReader class
68
Java Simplified / Session 22 / 69 of 45
Ex: Read from file, write out monitor
69
import java.io.*; public class FileRW_ex { public static void main(String[] args) throws IOException { FileReader fr=new FileReader("a.txt"); FileWriter fw=new FileWriter(FileDescriptor.out); //luong gan voi mh char[] b=new char[256]; int num; while((num=fr.read(b))>-1) { String upper=new String(b,0,num).toUpperCase(); fw.write(upper);
fw.flush(); } } }
Java Simplified / Session 22 / 70 of 45
It is a character based class that is useful for console output.
Provides support for Unicode characters. PrintWriter is a better alternative to
OutputStreamWriter and FileWriter. PrintWriter allows you to choose an
encoding by passing the encoding information to one of its constructors
PrintWriter class
70
Java Simplified / Session 22 / 71 of 45
Constructorspublic PrintWriter (File file)public PrintWriter (File file, String characterSet)public PrintWriter (String filepath)public PrintWriter (String filepath, String characterSet)public PrintWriter (OutputStream out)public PrintWriter (Writer out)
PrintWriter class
71
Java Simplified / Session 22 / 72 of 45
Write text which used the specificed encoding to file: Create object base on FileWriter classPrintWriter pw = new PrintWriter(new FileWriter(“Filename”) Create object base on FileOutputStream
classPrintWriter pw = new PrintWriter(new FileOutPutStream(“Filename”)
PrintWriter class: Write file text
72
Java Simplified / Session 22 / 73 of 45
Ex: Write lines of text to file using a PrintWriter
73
import java.io.FileWriter;import java.io.PrintWriter;public class PW_ex{ public static void main(String[] args) throws Exception { String filename = “aa.txt"; String[] linesToWrite = new String[] { "a", "b" }; boolean appendToFile = true; PrintWriter pw = null; if (appendToFile) { pw = new PrintWriter(new FileWriter(filename, true)); } else { pw = new PrintWriter(new FileWriter(filename)); } for (int i = 0; i < linesToWrite.length; i++) { pw.println(linesToWrite[i]); } pw.flush(); pw.close(); }}
Java Simplified / Session 22 / 74 of 45
Character Array Input / Output
Supports 8-bit character input and output CharArrayWriter adds the methods to the ones provided
by class Writer; some of these are:
Method Purposevoid reset( ) Resets the buffer int size( ) Returns the current size of the
buffer char [] toCharArray() Returns the character array copy
of the output buffer void writeTo(Writer w) throws IOException
Writes the buffer to another output stream
Supports input and output from memory buffers
Java Simplified / Session 22 / 75 of 45
ex Reads characters available from the Reader and returns these characters as a String object.
75
import java.io.CharArrayWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.Reader; import java.io.Writer;public class Main {public static final String readFully(Reader re) throws IOException {CharArrayWriter out = new CharArrayWriter(4096);transfer(re, out); out.close();return out.toString(); }public static final long transfer(Reader in, Writer out) throws IOException {long totalChars = 0;int charsInBuf = 0;char[] buf = new char[4096];while ((charsInBuf = in.read(buf)) != -1) {out.write(buf, 0, charsInBuf);totalChars += charsInBuf; }return totalChars;
}}
Java Simplified / Session 22 / 76 of 45
ByteStream & CharacterStream
76
Java Simplified / Session 22 / 77 of 45
Byte Stream thể hiện một loại dữ liệu nhấp xuất ở mức thấp, do đó nên tránh:◦ Nếu dữ liệu chứa những ký tự thì dùng character streams◦ Có những stream chứa nhiều kiểu dữ liệu phức tạp
Byte Stream chỉ nên sử dụng cho hầu hết những nhập xuất dữ liệu nguyên thủy
Sử dụng Byte Stream
77
Java Simplified / Session 22 / 78 of 45
Serialization Serializable ObjectInputStream ObjectOutputStream Example
Object Stream
78
Java Simplified / Session 22 / 79 of 45
Tuần tự hóa là quá trình chuyển (read/write) tập hợp các thể hiện đối tượng chứa các tham chiếu tới các đối tượng khác thành một luồng byte tuyến tính (tuần tự),
luồng này có thể được:◦ gửi đi qua một Socket, ◦ lưu vào tệp tin hoặc được ◦ xử lý dưới dạng một luồng dữ liệu.
Việc lưu đối tượng trên đĩa, dữ liệu trên tập tin là loại dữ liệu tuần tự (trải phẳng đối tượng ra theo thứ tự)
Tuần tự hóa đối tượng
Java Simplified / Session 22 / 80 of 45
Serialization
80
Java Simplified / Session 22 / 81 of 45
Chỉ có đối tượng thực thi giao diện Serializable mới có thể được ghi lại và được phục hồi bởi các tiện ích tuần tự hóa
một lớp thực thi giao diện Serializable thì lớp đó có khả năng tuần tự hóa->khả tuần tự hóa
khả tuần tự hóa
Java Simplified / Session 22 / 82 of 45
Object streams support I/O of objects◦ Like Data streams support I/O of primitive data types◦ The object has to be Serializable type
An object stream can contain a mixture of primitive and object values.
Input and Output of Complex Object:
Object Stream
82
Java Simplified / Session 22 / 83 of 45
There are two streams in java.io: ObjectInputStream and ObjectOutputStream .
They are like any other input stream and output stream with the difference that they can read and write objects
Serialization
83
Java Simplified / Session 22 / 84 of 45
This class has methods that support object serialization.
ObjectInputStream is responsible for reading objects from a input stream.
ObjectInputStream
84
InputStream
ObjectInput
DataInput
ObjectInputStreamImp
Java Simplified / Session 22 / 85 of 45
ObjectOutputStream is responsible for writting objects to the output stream
ObjectOutputStream
85
OutputStream
ObjectOutnput
DataOutnput
ObjectOutputStreamImp
Java Simplified / Session 22 / 86 of 45
public class writeObj { public static void main(String[] args) throws Exception { Junk obj1 = new Junk("Lê Xuân Anh"); Junk obj2 = new Junk("Lê QuốMc Ba"); ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("b.txt")));
objectOut.writeObject(obj1); // Write object objectOut.writeObject(obj2); // Write object objectOut.close(); // Close the output stream
ObjectInputStream objectIn = null; int Count = 0; Junk object = null;objectIn = new ObjectInputStream(new BufferedInputStream(new FileInputStream("b.txt")));
while (Count < 2) { object = (Junk) objectIn.readObject(); Count++; System.out.println("Object " + Count + ": " + object.toStr()); } objectIn.close(); }}
Example Serialization
86
class Junk implements Serializable { String str; public Junk(String s) { str = s; } public String toSt(){ return str; }}
Java Simplified / Session 22 / 87 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
Summarization
87
Recommended