Chapter3 IO
Chapter3 IO
GTVT TP.HCM
3 Nhá0-p/Xuá0¥t chuá°©n
VÃ- dụ
* Thá»±c hiá»ịn phép toÃjn chia cho 0.
Checked Exception
* ẢŨ.E°á»£c sá»- dụng trong signature cá»§a method
Stream là g×?
* In computer science Streams are defined as the sequence of data
elements that
is made available over time. It represents a Source (which generates the
data in
the form of Stream) and a destination (which consumes or read data available
as Stream).
* In other simple words it is a flow of data from which you can read or
write data
to it.
Input stream
Output stream
* System.in = bà n phÃ-m
* System.out = mà n h×nh
* Truy xuá°¥t file vẢfn bá°£n: dá» liá»ịu trong file Ả'.E°á»£c xem nhf°
dãy cÃjc mã Unicode
cá»§a cÃjc kÃ- tá»±. *
* Serialize & Deserialize: truy xuá°¥t file lfi°u trá» cÃjc objects.
}
}
Khoa CNTT (ẢŨH GTVT TP.HCM) Java Programming
18 / 24
Truy xuá°¥t File
Ảũá»ũc file vẢfn bá°£n: Ả'á»ũc từng dÃ2ng public static
void docFileByScanner() { try {File f = new
File("vanban.txt"); if (!f.exists()) {
throw new Exception("File khong ton tai");
}
Scanner scan = new Scanner(f);
String line;
while (scan.hasNextLine()) { line = scan.nextLine();
System.out.println(line);
}scan.close();
} catch (Exception ex) {/*...*/}
}
Serialize
public static void ghiDSHHSerialize() {
File f = new File("hh.dat");
FileOutputStream fo = null;
ObjectOutputStream out = null; try {
fo = new FileOutputStream(f); out = new
ObjectOutputStream(fo);
out.writeObject(HangHoa.dsHangHoa());//note! } catch
(Exception ex) {/*...*/} finally { try {
out .close(); fo. close () ;
} catch (IOException ex) {/*...*/}
}
}
Deserialize
public static void docDSHHSerialize() {
File f = new File("hh.dat");
FileInputStream fo = null;
ObjectInputStream out = null; try {
fo = new FileInputStream(f); out = new
ObjectInputStream(fo); ArrayList<HangHoa> lst;
lst = (ArrayList<HangHoa>)out.readObject(); for(HangHoa
h:lst)
System.out.println(h.toString() );
} catch (Exception ex) {/*...*/} finally { try {
out.close();fo.close();
} catch (IOException ex) {/*...*/}}
}
BÃ i tá °-p
Sá»- dụng cÃjc kiá°£,n thức cá»§a ch.E°.Ejng nà y (exception
xÃíy dá»±ng ch.E°.Ejng & streams),
tr×nh minh há»ũa quÃj tr×nh mua bÃjn hà ng hÃ3a. Gá»"m cÃjc
nẢfng sau: chức
1 Hiá»fn thá»< danh sÃjch hà ng hÃ3a.