You are on page 1of 51

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 7. Lung v x l file
Khi nim lung Cc lung byte i tng serializable Cc lung k t File truy cp ngu nhin Lp File Bi tp

Khi nim lung (stream)


Lung l mt dng chy ca d liu c gn vi cc thit b vo ra. Hai loi lung:
Lung nhp: Gn vi cc thit b nhp nh bn phm, my scan, file... Lung xut: Gn vi cc thit b xut nh mn hnh, my in, file...

Vic x l vo ra thng qua lung gip cho lp trnh vin khng phi quan tm n bn cht ca thit b vo ra.
3

Khi nim lung (stream)


Chng trnh c trn lung nhp ly d liu t thit b nhp, ghi vo lung xut a d liu ra thit b xut
Input Stream
Input Device

Program
Output Device

Output Stream
4

Cc lung c bn
Lung byte: L dng chy cc byte
InputStream: Lung nhp byte c bn OutputStream: Lung xut byte c bn

Lung k t: L dng chy cc k t (char)


Reader: Lung nhp k t c bn Writer: Lung xut k t c bn

Cc lp lung nm trong gi java.io

Lung byte
ByteArrayInputStream DataInputStream FileInputStream FilterInputStream InputStream ObjectInputStream PipedInputStream SequenceInputStream StringBufferInputStream
6

BufferedInputStream LineNumberInputStream PushbackInputStream

Lung byte
ByteArrayOutputStream DataOutputStream FileOutputStream FilterOutputStream OutputStream ObjectOutputStream PipedOutputStream BufferedOutputStream PrintStream

Lung nhp/xut byte c bn


InputStream v OutputStream l hai lp gc ca mi lung nhp/xut byte (abstract).
Object

InputStream

OutputStream

Lp InputStream
Mt s phng thc ca InputStream
abstract int read() throws IOException c mt byte t lung. Nu cui lung s tr v -1 int read(byte[] b) throws IOException c mt dy byte t lung void close() throws IOException ng lung nhp int available() throws IOException Tr v s byte c th c tip long skip(long n) throws IOException B qua n byte
9

Lp OutputStream
Mt s phng thc ca OutputStream
abstract void write(int b) throws IOException Ghi mt byte ra lung void write(byte[] b) throws IOException Ghi mt dy byte ra lung void close() throws IOException ng lung void flush() throws IOException Dn xut lung

10

Cc lung file
c s dng xut nhp vi file. Lung nhp t file: FileInputStream
FileInputStream(String name) FileInputStream(File f)

Lung xut ra file: FileOutputStream


FileOutputStream(String name) FileOutputStream(File f) FileOutputStream(String name, boolean append)

Phng thc nhp/xut ca cc lung file ging nh ca cc lung nhp xut c bn


11

V d: c v hin 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 liu ra file


import 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"); } } }
13

Lung lc (filter stream)


Lung lc c kh nng kt ni vi cc lung khc v x l d liu theo cch ring ca n. FilterInputStream v FilterOutputStream l 2 lp lung lc c bn.
Filter Stream Input Stream
Input Device

14

Lung nhp/xut d liu s cp


DataInputStream v DataOutputStream l 2 lp lc cho php nhp xut d liu thuc cc kiu s cp.
DataInputStream
char long float ...

Input Stream
Input Device

15

Lung nhp/xut d liu s cp


Mt s phng thc ca DataInputStream
float readFloat() throws IOException int readInt() throws IOException long readLong() throws IOException String readUTF() thr ows IOException void void void void writeFloat(float v) throws IOException writeInt(int b) throws IOException writeLong(long v) throws IOException writeUTF(String s) throws IOException

Mt s phng thc ca DataOutputStream

16

V d: To file cc s ngu nhin


try { FileOutputStream f = new FileOutputStream("randnum.dat"); DataOutputStream outFile = new DataOutputStream(f); for(int i = 0; i < 20; i++) outFile.writeInt( (int) (Math.random()*1000) ); outFile.close(); } catch (IOException e) { ... }

FileInputStream g = new FileInputStream("randnum.dat"); DataInputStream inFile = new DataInputStream(g); int num; while (true) { num = inFile.readInt(); System.out.println("num = " + num); } } catch (EOFException e) { System.out.println("End of file"); 17 } catch (IOException e) { ... }

try {

Lung m (buffered stream)


Lung m gip gim bt s ln c ghi d liu trn thit b vo ra, tng tc nhp/xut. Cc lp lung m
BufferedInputStream (m nhp) BufferedOutputStream (m xut)

18

V d: c v hin th file (v2)


// version 2 ny c th em li hiu qu ng k hn version 1 trn // nhng file c kch thc ln try { FileInputStream f = new FileInputStream("readme.txt"); BufferedInputStream inFile = new BufferedInputStream(f); int ch; while ( (ch = inFile.read()) != -1 ) { System.out.print((char)ch); } } catch (IOException e) { System.out.println("Error IO file"); }

19

Ghp ni nhiu lung


C th dng lung lc ghp ni nhiu lung vi nhau. V d:
FileInputStream fStream = new FileInputStream("data.dat"); BufferedInputStream bStream = new BufferedInputStream(fStream); DataInputStream dStream = new DataInputStream(bStream); ... dStream.close();

20

System.in v System.out
System.in
i tng nhp chun, gn vi bn phm. Thuc lp InputStream.

System.out
i tng xut chun, gn vi mn hnh. Thuc lp PrintStream.

Lp PrintStream
Cho php hin th biu din ca d liu. PrintStream k tha t FilterOutputStream
21

Lp PrintStream
// Chng trnh ny c mt file cc s thc v ghi vo file khc // di dng vn bn try { FileInputStream f = new FileInputStream("float.dat"); DataInputStream inStream = new DataInputStream(f); FileOutputStream ff = new FileOutputStream("ketqua.txt"); PrintStream pStream = new PrintStream(ff); int count = 0; while (true) { float num = inStream.readFloat(); count++; pStream.println("Float " + count + " = " + num); } inStream.close(); pStream.close(); } catch (EOFException e) { System.out.println(End of file); } catch (IOException e) {...}

22

Bi tp ti lp
Bi 1: Vit chng trnh m xem trong mt file vn bn cho trc c bao nhiu cu. Bit rng cc cu kt thc bi du chm. Bi 2: Vit chng trnh to file ghi 100 s Fibonacci u tin. Vit chng trnh th hai c v hin th d liu t file ny.

23

Lung nhp/xut i tng


lu li mt i tng, ta c th lu ln lt tng thuc tnh ca n. Khi c li i tng ta phi to i tng mi t cc thuc tnh ghi. => Di dng, km linh hot. Java h tr c/ghi cc i tng mt cch n gin thng qua lp ObjectInputStream v ObjectOutputStream. Mt i tng mun c th c c/ghi phi ci t giao tip java.io.Serializable
24

V d: Ghi li tn v ngy sinh


try {

FileOutputStream f = new FileOutputStream("birthfile.dat"); ObjectOutputStream oStream = new ObjectOutputStream(f); String babyName = "Briney Spears"; Date today = new Date(); oStream.writeObject(babyName); oStream.writeObject(today);

oStream.close(); } catch (IOException e) { System.out.println(Error IO file); }

25

V d: c tn v ngy sinh
try { FileInputStream f = new FileInputStream("birthfile.dat"); ObjectInputStream inStream = new ObjectInputStream(f); String name = (String) inStream.readObject(); Date birthDate = (Date) inStream.readObject(); System.out.println("Name of baby: " + name); System.out.println("Birth date: " + birthDate); inStream.close(); } catch (IOException e) { System.out.println(Error IO file); } catch (ClassNotFoundException e) { System.out.println(Class of serialized object not found); }
26

c/ghi i tng t to
// file Student.java public class Student implements Serializable

private String name; private int age;

Student(String name, int age) { this.name = name; this.age = age; }


public String toString() { String ret = "My name is " + name + "\nI am " + age + " years old"; return ret; }
27

c/ghi i tng t to
// file WriteMyObject.java import java.io.*; public class WriteMyObject { public static void main(String[] args) { try { FileOutputStream f = new FileOutputStream("student.dat"); ObjectOutputStream oStream = new ObjectOutputStream(f); Student x = new Student("Bill Gates", 18); oStream.writeObject(x); oStream.close(); } catch (IOException e) { System.out.println(Error IO file); }
28

c/ghi i tng t to
FileInputStream g = new FileInputStream("student.dat"); ObjectInputStream inStream = new ObjectInputStream(g); Student y = (Student) inStream.readObject(); System.out.println(y.toString()); inStream.close(); } catch (ClassNotFoundException e) { System.out.println(Class not found); } catch (IOException e) { System.out.println(Error IO file); } try {

29

c/ghi i tng t to
i tng c th ci t 2 phng thc sau thc hin c/ghi theo cch ring ca mnh.
private void writeObject(ObjectOutputStream out) throws IOException private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException

30

Lung k t
T Jdk 1.1, Java h tr c v thao tc trn lung i vi cc k t Unicode (2 byte). Lung k t c bn
Reader (c) Writer (ghi)
Object

Reader

Writer
31

Lung k t
CharArrayReader InputStreamReader FilterReader Reader StringReader PipedReader BufferedReader LineNumberReader FileReader PushBackReader

32

Lung k t
CharArrayWriter OutputStreamWriter FilterWriter Writer StringReader PipedWriter BufferedWriter StringWriter
33

FileWriter

Kt ni lung byte v lung k t


C th chuyn t lung byte sang lung k t nh cc lp
InputStreamReader OutputStreamReader

V d:
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in)); String s = buff.readLine(); ...

34

Lung k t v Unicode
Unicode Encoding
UTF-8 UTF-16

c/ghi file vi cc k t Unicode


Kt ni t lung FileInputStream/FileOutputStream vo InputStreamReader/OutputStreamWriter (c th vo tip BufferedReader/BufferedWriter) Ch r cch encoding
35

V d: Ghi file Unicode


try { OutputStreamWriter buff = new OutputStreamWriter(new FileOutputStream("unicode.txt"), "UTF-16"); buff.write(''); buff.write(''); String s = "\r\nvy h"; buff.write(s, 0, s.length()); buff.close(); } catch (IOException e) { System.out.println(Error IO file); }

36

V d: c file Unicode
try { InputStreamReader buff = new InputStreamReader(new FileInputStream("unicode.txt"), "UTF-16"); int ch; while ( (ch = buff.read()) != -1) { System.out.print((char)ch); // ch console s khng hin th c k t c // du, nn hin th trong TextField hoc TextArea } buff.close(); } catch (IOException e) { System.out.println(Error IO file); }

37

Ch khi son tho m


Mun a trc tip ting Vit Unicode vo cng cc on m Java cn phi s dng Notepad hoc cc phn mm h tr son tho ting Vit. Cc bc cn thc hin
Lu file source code di dng Unicode G lnh bin dch
javac encoding unicode filename.java

Lnh thng dch


java filename (nh bnh thng)
38

File truy nhp ngu nhin


Hai hn ch ca vic x l file thng qua lung
Khng th c v ghi file cng mt lc Truy nhp file mang tnh tun t

Java h tr vic truy nhp v x l file mt cch t do thng qua lp RandomAccessFile.

39

File truy nhp ngu nhin


Cc phng thc c bn
RandomAccessFile(String name, String mode) // cu t, trong mode c th l r, w, rw int readInt(); // c s nguyn void writeInt(int v); // ghi s nguyn long readLong(); // c s long void writeLong(long v); // ghi s long void seek(long pos); // di chuyn v tr con tr file long getFilePointer(); // ly v tr ca con tr file long length(); // ly kch c ca file void close(); // ng file ...
40

V d vi RandomAccessFile
try { RandomAccessFile f = new RandomAccessFile("randfile.dat","rw"); f.writeBoolean(true); f.writeInt(123456); f.writeChar('j'); f.writeDouble(1234.56); f.seek(1); System.out.println(f.readInt()); System.out.println(f.readChar()); System.out.println(f.readDouble()); Kt qu f.seek(0); System.out.println(f.readBoolean()); 123456 f.close(); j } catch (IOException e) { 1234.56 System.out.println(Error IO file); true }
41

Ch khi ng file
Nu lnh f.close() trong khi try th c th lnh ny s khng c thc hin khi c li cc lnh pha trn. C th vit li nh sau:

42

Ch khi ng file
FileInputStream f = null; try { f = new FileInputStream("somefile.txt"); // c file } catch (IOException e) { // hin th li } finally { if (f != null) { try { f.close(); // ng file } catch (Exception e) { // thng bo li khi ng file } } }
43

Lp File
Lp File cho php ly thng tin v file v th mc. Mt s phng thc ca File
boolean exists(); // kim tra s tn ti ca file boolean isDirectory(); // kim tra xem file c phi l th mc String getParent(); // ly th mc cha long length(); // ly c file (byte) long lastModified(); // ly ngy sa file gn nht String[] list(); // ly ni dung ca th mc

44

V d: Hin th thng tin file


import java.io.*; import java.util.Date; public class FileInfo { public static void main(String[] args) { File file = new File("randfile.dat"); if ( file.exists() ) { System.out.println("Path is: " + file.getAbsolutePath()); System.out.println("It's size is: " + file.length()); Date dateModified = new Date(file.lastModified()); System.out.println("Last update is: " + dateModified); } else System.out.println("The file does not exist"); } }
45

V d: Hin ni dung th mc
import java.io.*; public class DirList { public static void main(String[] args) { File dir = new File(".", ""); if ( dir.isDirectory() ) { String[] subFiles = dir.list(); for(int i=0; i < subFiles.length; i++) if (new File(subFiles[i]).isDirectory()) System.out.println(subFiles[i] + " <DIR>"); else System.out.println(subFiles[i]); } else System.out.println("The file is not a directory"); } }

46

Tm tt v x l file
Nn dng DataInputStream v DataOutputStream nhp/xut cc d liu kiu s cp (int, float...) Nn dng ObjectInputStream v ObjectOutputStream nhp/xut cc i tng. Nn kt hp lung file v lung c/ghi k t nhp xut cc file k t Unicode. Nn dng RandomAccessFile nu mun c/ghi t do trn file. Dng lp File ly thng tin v file
47

Mt s lp khc
java.io.StreamTokenizer

java.io.FilenameFilter java.awt.FileDialog javax.swing.JFileChooser ...

48

Bi tp
1. Vit chng trnh mycopy s dng nh sau: java mycopy filename1 filename2
Nu filename1 v filename2 l 2 file th chng trnh copy ni dung ca filename1 sang filename2 Nu filename2 l th mc th copy filename1 sang th mc filename2 Nu filename1 c tn l con th cho php to filename2 vi ni dung g t bn phm (ging lnh copy con)

2. Vit chng trnh mydir s dng nh sau: java mydir filename. Chng trnh c chc nng ging lnh dir ca DOS.
49

Bi tp
3. Vit chng trnh cho php ngi dng chn mt file vn bn, sau hin th ni dung ca file ny trong mt i tng TextArea. (Dng lp JFileChooser m hp thoi chn file). 4. Vit chng trnh c cu trc ca mt nh bitmap v hin th ra mn hnh. Tham kho cu trc nh bitmap trn Internet.

50

Bi tp
5. Vit chng trnh qun l mt danh sch th sinh (Candidate). Chng trnh cho php thm th sinh, tm kim, cp nht... Khi bt u, chng trnh s ly d liu t file thisinh.dat. Khi kt thc, chng trnh ghi li danh sch sinh vin vo file. C th dng RandomAccessFile hoc dng ObjectOutputStream v ci t Serializable.

51

You might also like