You are on page 1of 136

Chng 3

LUNG D LIU

Ni dung
X l bit l
Lung d liu
Thao tc trn tp tin

Exception Handling
X l mi s dng c ch bit l
trong Java

Cc cch x l li
S dng cc mnh iu kin kt hp
vi cc gi tr c.
S dng c ch x l bit l.

V d: Lp Inventory
public class Inventory
{
public final int MIN = 0;
public
final int MAX = 100;
public final int CRITICAL = 10;
public boolean addToInventory (int amount)
{
int temp;
temp = stockLevel + amount;
if (temp > MAX)
{
System.out.print("Adding " + amount + " item will cause stock ");
System.out.println("to become greater than " + MAX + " units
(overstock)");
return false;
}

V d: Lp Inventory (2)
else
{
stockLevel = stockLevel + amount;
return true;
}
} // End of method addToInventory
:

Cc vn i vi cch tip
cn iu kin/c
reference1.method1 ()
if (reference2.method2() == false)
return false;

reference2.method2 ()
if (store.addToInventory(amt) == false)
return false;

store.addToInventory (int amt)


if (temp > MAX)
return false;

Cc vn i vi cch tip
cn iu kin/c
reference1.method1 ()
if (reference2.method2() == false)
return false;

Vn 1: Phng thc
ch c th qun kim tra
iu kin tr v

reference2.method2 ()
if (store.addToInventory(amt) == false)
return false;

store.addToInventory (int amt)


if (temp > MAX)
return false;

Cc vn i vi cch tip
cn iu kin/c
reference1.method1 ()
if (reference2.method2() == false)
return false;

reference2.method2 ()
if (store.addToInventory(amt) == false)
return false;

Vn 2: Phi s dng
1 lot cc php kim tra
gi tr c tr v

store.addToInventory (int amt)


if (temp > MAX)
return false;

Cc vn i vi cch tip
cn iu kin/c
reference1.method1 ()
if (reference2.method2() == false)
return false;

reference.method2 ()
if (store.addToInventory(amt) == false)
return false;
??
??

Vn 3: Phng thc
ch c th khng bit
cch x l khi li xy ra

store.addToInventory (int amt)


if (temp > MAX)
return false;

Cc cch x l li
S dng cc mnh iu kin kt hp
vi cc gi tr c.
S dng c ch x l bit l.

X l bit l
C php:
try
{
// Code that may cause an error/exception to occur
}
catch (ExceptionType identifier)
{
// Code to handle the exception
}

X l bit l:
c d liu t bn phm
import java.io.*;
class Driver
{
public static void main (String [] args)
{
BufferedReader stringInput;
InputStreamReader characterInput;
String s;
int num;
characterInput = new InputStreamReader(System.in);
stringInput = new BufferedReader(characterInput);

X l bit l:
c d liu t bn phm
try
{
System.out.print("Type an integer: ");
s = stringInput.readLine();
System.out.println("You typed in..." + s);
num = Integer.parseInt (s);
System.out.println("Converted to an integer..." + num);
}
catch (IOException e)
{
System.out.println(e);
}
catch (NumberFormatException e)
{
:
:
:
}
}
}

X l bit l:
Bit l xy ra khi no
try
{
System.out.print("Type an integer: ");
s = stringInput.readLine();
System.out.println("You typed in..." + s);
num = Integer.parseInt (s);
System.out.println("Converted to an integer..." + num);
}

Kt qu ca phng thc
readLine()
try
{
System.out.print("Type an integer: ");
Bit l c th xy ra
s = stringInput.readLine();
y
System.out.println("You typed in..." + s);
num = Integer.parseInt (s);
System.out.println("Converted to an integer..." + num);
}

Lp BufferedReader
http://java.sun.com/j2se/1.4.1/docs/api/java/io/BufferedReader.html

public class BufferedReader


{
public BufferedReader (Reader in);
public BufferedReader (Reader in, int sz);
public String readLine () throws IOException;
:
}

Kt qu ca phng thc
parseInt ()
try
{
System.out.print("Type an integer: ");
s = stringInput.readLine();
System.out.println("You typed in..." + s);
Bit l c th xy ra
num = Integer.parseInt (s);
y
System.out.println("Converted to an integer..." + num);
}

Lp Integer

http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Integer.html

public class Integer


{
public Integer (int value);
public Integer (String s) throws NumberFormatException;
:
:
public static int parseInt (String s) throws NumberFormatException;
:
:
}

C ch x l bit l
try
{
System.out.print("Type an integer: ");
s = stringInput.readLine();
System.out.println("You typed in..." + s);
num = Integer.parseInt (s);
System.out.println("Converted to an integer..." + num);
}
catch (IOException e)
{
System.out.println(e);
}
catch (NumberFormatException e)
{
:
:
:
}
}
}

C ch x l bit l

Driver.main ()
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
:
}

Integer.parseInt (String s)
{
:
:
}

C ch x l bit l
Integer.parseInt (String s)
{

Driver.main ()
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
:
}

Ngi s dng khng nhp


} chui s

C ch x l bit l
Integer.parseInt (String s)
{

Driver.main ()
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
:
}

NumberFormatException e =
new
}
NumberFormatException ();

C ch x l bit l
Integer.parseInt (String s)
{

Driver.main ()
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
:
}

NumberFormatException e =
new
}
NumberFormatException ();

C ch x l bit l
Integer.parseInt (String s)
{

Driver.main ()
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
}
Bit l s c x l y

Bt bit l
catch (NumberFormatException e)
{
:
:
:
}
}
}

Bt bit l
catch (NumberFormatException e)
{
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
}
}
}

Bt bit l

catch (NumberFormatException e)

Nhp vo: exception"

System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
java.lang.NumberFormatExcept
}
ion: For input string:
exception"

java.lang.NumberFormatException: For input string: exception"


at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:
48)
at java.lang.Integer.parseInt(Integer.java:426)
at java.lang.Integer.parseInt(Integer.java:476)
at Driver.main(Driver.java:39)

Cc loi bit l
Bit l khng cn kim tra
Bit l phi kim tra

c im ca bit l khng cn
kim tra
Trnh bin dch khng yu cu phi bt cc bit l khi
n xy ra.
Khng cn khi try-catch

Cc bit l ny c th xy ra bt c thi im no khi


thi hnh chng trnh.
Thng thng l nhng li nghim trng m chng
trnh khng th kim sot
X dng cc mnh iu kin x l s tt hn.

V d:
NullPointerException,IndexOutOfBoundsException,
ArithmeticException

Bit l khng cn kim tra:


NullPointerException
int [] arr = null;
arr[0] = 1;
arr = new int [4];
int i;
for (i = 0; i <= 4; i++)
arr[i] = i;
arr[i-1] = arr[i-1] / 0;

NullPointerException

Bit l khng cn kim tra: :


ArrayIndexOutOfBoundsException
int [] arr = null;
arr[0] = 1;
arr = new int [4];
int i;
for (i = 0; i <= 4; i++)
arr[i] = i;
arr[i-1] = arr[i-1] / 0;

ArrayIndexOutOfBoundsException
(when i = 4)

Bit l khng cn kim tra: :


ArithmeticExceptions
int [] arr = null;
arr[0] = 1;
arr = new int [4];
int i;
for (i = 0; i <= 4; i++)
arr[i] = i;
arr[i-1] = arr[i-1] / 0;

ArithmeticException
(Division by zero)

Bit l cn phi kim tra


Phi x l khi bit l c kh nng xy ra
Phi s dng khi try-catch

Lin quan n 1 vn c th
Khi mt phng thc c gi thi hnh

V d:
IOException

Trnh b qua vic x l bit l


try
{
s = stringInput.readLine();
num = Integer.parseInt (s);
}
catch (IOException e)
{
//System.out.println(e);
}

Trnh b qua vic x l bit l

try
{

NO!

s = stringInput.readLine();
num = Integer.parseInt (s);
}
catch (IOException e)
{
System.out.println(e);
}
catch (NumberFormatException e)
{
// Do nothing here but set up the try-catch block to bypass the
// annoying compiler error
}

Checked vs Unchecked

Mnh finally
L 1 mnh khng bt buc trong khi try-catchfinally.
Dng t khi lnh s c thi hnh bt k bit
l c xay ra hay khng.

Mnh finally: c bit l


Foo.method ()
{
try
{

}
f.method();

catch
{
}

finally
{
}

Mnh finally: c bit l


h lm
n

l
u
t c
m
h
n
h
1) Thi
bit l
a
r
y
x

try
{
f.method();
}

catch
{
}

finally
{
}

t
b
c

t l l

i
3) B i v x
l

4) Thi hnh cc cu
lnh trong khi finally

f.method ()
{
2) Bit l c to ra
}

Mnh finally: khng c bit l


try
{
f.method();

ng

h
p
nh 1
inh

s
h
t
i

h
h
t
p
i
1) G khng lm
thc
bit l

catch
{
}

finally
{
}

u ally
c
c i fin
c
nh g kh

i h ron
h
t
T
3) lnh

f.method ()
{
2) Phng thc thi
hnh bnh thng
}

Try-Catch-Finally: V d
class Driver
{
public static void main (String [] args)
{
TCFExample eg = new TCFExample ();
eg.method();
}
}

Try-Catch-Finally: V d
public class TCFExample
{
public void method ()
{
BufferedReader br;
String s;
int num;
try
{
System.out.print("Type in an integer: ");
br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
num = Integer.parseInt(s);
return;
}

Try-Catch-Finally: V d
catch (IOException e)
{
e.printStackTrace();
return;
}
catch (NumberFormatException e)
{
e.printStackTrace ();
return;
}
finally
{
System.out.println("<<<This code will always execute>>>");
return;
}
}
}

Hm c gi khng th x l
bit l
method 2 ()
Exception
thrown!

method 1 ()
???

main ()

Hm c gi khng th x l
bit l

import java.io.*;

public class TCExample


{

public void method () throws IOException, NumberFormatException


{
BufferedReader br;
String s;
int num;
System.out.print("Type in an integer: ");
br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
num = Integer.parseInt(s);
}
}

Hm c gi khng th x l
bit l
class Driver
{
public static void main (String [] args)
{
TCExample eg = new TCExample ();
boolean inputOkay = true;

Hm c gi khng th x l
bit l

do
{
try
{
eg.method();
inputOkay = true;
}
catch (IOException e)
{
e.printStackTrace();
}
catch (NumberFormatException e)
{
inputOkay = false;
System.out.println("Please enter a whole number.");
}
} while (inputOkay == false);
} // End of main
}
// End of Driver class

Hm c gi khng th x l
bit l
class Driver
{
public static void main (String [] args)
{
TCExample eg = new TCExample ();
boolean inputOkay = true;

Hm c gi khng th x l
bit l
do
{
try
{
eg.method();
inputOkay = true;
}
catch (IOException e)
{
e.printStackTrace();
}
catch (NumberFormatException e)
{
inputOkay = false;
System.out.println("Please enter a whole number.");
}
} while (inputOkay == false);
}// End of main
} // End of Driver class

Hm c gi khng th x l
bit l
class Driver
{
public static void main (String [] args)
{
TCExample eg = new TCExample ();
boolean inputOkay = true;

Hm c gi khng th x l
bit l

do
{
try
{
eg.method();
inputOkay = true;
}
catch (IOException e)
{
e.printStackTrace();
}
catch (NumberFormatException e)
{
inputOkay = false;
System.out.println("Please enter a whole number.");
}
} while (inputOkay == false);
} // End of main
}
// End of Driver class

Hm main() khng x l bit l

class Driver
{
public static void main (String [] args) throws IOException,
NumberFormatException
{
TCExample eg = new TCExample ();
eg.method();
}
}

To ra kiu bit l mi
Throwable

Error

VirtualMachineError

Exception

IOException

OutOfMemoryError
Excerpt from Big Java by C. Horstmann p. 562

???

RunTime
Exception

Lp Exception
Exception

ClassNotFound
Exception

EOFException

IOException

FileNotFound
Exception

CloneNotFound
Exception

MalformedURL
Exception

UnknownHost
Exception

To bit l mi
class Driver
{
public static void main (String [] argv)
{
Inventory chinookInventory = new Inventory ();
CommandProcessor userInterface = new
CommandProcessor
(chinookInventory);
userInterface.startProcessingInput ();
}
}

To bit l mi
public class CommandProcessor
{
private char menuOption;
private Inventory storeInventory;
public CommandProcessor (Inventory storeToTrack)
{
menuOption = 'q';
storeInventory = storeToTrack;
}

To bit l mi
public void startProcessingInput ()
{
do
{
displayMenu();
readMenuOption();
switch (menuOption)
{
case 'a':
case 'A':
storeInventory.getAmountToAdd();
break;
case 'r':
case 'R':
storeInventory.getAmountToRemove();
break;

To bit l mi
case 'd':
case 'D':
storeInventory.displayInventoryLevel();
break;
case 'c':
case 'C':
if (storeInventory.inventoryTooLow())
System.out.println("Stock levels critical!");
else
System.out.println("Stock levels okay");
storeInventory.displayInventoryLevel();
break;
case 'q':
case 'Q':
System.out.println("Quitting program");
break;

To bit l mi
default:
System.out.println("Enter one of A, R, D, C or Q");
}
} while ((menuOption != 'Q') && (menuOption != 'q'));
} // End of method startProcessingInput

To bit l mi
protected void displayMenu ()
{
System.out.println("\n\nINVENTORY PROGRAM: OPTIONS");
System.out.println("\t(A)dd new stock to inventory");
System.out.println("\t(R)emove stock from inventory");
System.out.println("\t(D)isplay stock level");
System.out.println("\t(C)heck if stock level is critical");
System.out.print("\t(Q)uit program");
System.out.println();
System.out.print("Selection: ");
}
protected void readMenuOption ()
{
menuOption = (char) Console.in.readChar();
Console.in.readLine();
System.out.println();
}
} // End of class CommandProcesor

Lp Inventory
public class Inventory
{
public final static int CRITICAL = 10;
public final static int MIN = 0;
public final static int MAX = 100;
private int stockLevel;
private boolean amountInvalid;

Lp Inventory
public void getAmountToAdd ()
{
int amount;
do
{
System.out.print("No. items to add: ");
amount = Console.in.readInt();
Console.in.readLine();
try
{
addToInventory(amount);
amountInvalid = false;
}

Lp Inventory
catch (InventoryOverMaxException e)
{
System.out.println(e);
System.out.println("Enter another value.");
System.out.println();
amountInvalid = true;
}
finally
{
displayInventoryLevel();
}
} while (amountInvalid == true);
}
// End of method getAmountToAdd

Lp Inventory
public void getAmountToRemove ()
{
int amount;
do
{
System.out.print("No. items to remove: ");
amount = Console.in.readInt();
Console.in.readLine();
try
{
removeFromInventory(amount);
amountInvalid = false;
}

Lp Inventory
catch (InventoryBelowMinException e)
{
System.out.println(e);
System.out.println("Enter another value.");
System.out.println();
amountInvalid = true;
}
finally
{
displayInventoryLevel();
}
} while (amountInvalid == true);
}
// End of method getAmountToRemove

Lp Inventory
private void addToInventory (int amount) throws InventoryOverMaxException
{
int temp;
temp = stockLevel + amount;
if (temp > MAX)
{
throw new InventoryOverMaxException ("Adding " + amount + " item
will cause stock to become greater than " + MAX + " units");
}
else
{
stockLevel = stockLevel + amount;
}
}

Lp Inventory
private void removeFromInventory (int amount) throws
InventoryBelowMinException
{
int temp;
temp = stockLevel - amount;
if (temp < MIN)
{
throw new InventoryBelowMinException ("Removing " + amount
+ " item will cause stock to become less than " + MIN + " units");
}
else
{
stockLevel = temp;
}
}

Lp Inventory
public boolean inventoryTooLow ()
{
if (stockLevel < CRITICAL)
return true;
else
return false;
}
public void displayInventoryLevel ()
{
System.out.println("No. items in stock: " + stockLevel);
}
}

// End of class Inventory

Lp
InventoryOverMaxException
public class InventoryOverMaxException extends Exception
{
public InventoryOverMaxException ()
{
super ();
}
public InventoryOverMaxException (String s)
{
super (s);
}
}

Lp
InventoryBelowMinException
public class InventoryBelowMinException extends Exception
{
public InventoryBelowMinException ()
{
super();
}
public InventoryBelowMinException (String s)
{
super(s);
}
}

Nhc li tha k
C th thay th mt i tng ca lp con
cho 1 i tng ca lp cha (ngc li
khng ng).
Monster
A Monster is
not a
Dragon
A Dragon is
not a
BlueDragon

Dragon
A Dragon is a
Monster

BlueDragon

A BlueDragon is a
Dragon

Cy tha k ca lp
IOExceptions
IOException

These classes are


instances of class
IOException
EOFException

FileNotFound
Exception

Tha k v vn bt bit l
Khi x l mt chui cc bit l cn phi
m bo rng cc bit l lp con c x
l trc cc bit l ca lp cha.
X l cc trng hp c th trc khi x
l cc trng hp tng qut

Tha k v vn bt bit l
ng

Sai

try
{

try
{

}
catch (EOFException e)
{

}
catch (IOException e)
{

}
catch (IOException e)
{

}
catch (EOFException e)
{

Qun L Tp Tin & Th Mc


java.lang.Object
+--java.io.File
Lp File khng phc v cho vic nhp/xut d liu trn
lung. Lp File thng c dng bit c cc
thng tin chi tit v tp tin cng nh th mc (tn, ngy
gi to, kch thc, )

X l th mc Lp File
Cc Constructor:
To i tng File t ng dn tuyt i
public File(String pathname)
v d: File f = new File(C:\\Java\\vd1.java);
To i tng File t tn ng dn v tn tp tin tch bit
public File(String parent, String child)
v d: File f = new File(C:\\Java, vd1.java);
To i tng File t mt i tng File khc
public File(File parent, String child)
v d: File dir = new File (C:\\Java);
File f = new File(dir, vd1.java);

X l th mc Lp File
Mt s phng thc thng gp ca lp File
public String getName()

Ly tn ca i tng File

public String getPath()

Ly ng dn ca tp tin

public boolean isDirectory() Kim tra xem tp tin c phi l th mc khng?


public boolean isFile()

Kim tra xem tp tn c phi l mt file khng?

public String[] list()

Ly danh sch tn cc tp tin v th mc con ca


i tng File ang xt v tr v trong mt
mng.

X l trn th mc, tp tin


public void copyDirectory(File srcDir, File dstDir) throws IOException {
if (srcDir.isDirectory()) {
if (!dstDir.exists()) { dstDir.mkdir(); }
String[] children = srcDir.list();
for (int i=0; i<children.length; i++) { copyDirectory(new File(srcDir,
children[i]), new
File(dstDir, children[i]));
}
}
else {
copyFile(srcDir, dstDir);
}
}

Nhp/xut d liu
Nhp xut d liu trong Java da trn m hnh lung d liu
OutputStrea
m

File(s)
InputStream

Your
Program
Another
Program
Other Devices

am
e
r
St
t
n
Pri

Lp System c: in, out


System.out l 1 th hin ca lp
PrintStream.
PrintStream c phng thc print,
println ghi d liu xung lung.

CIE OOP

80

Nhp xut d liu


D liu c th n t bt k ngun no v
xut ra bt k ni no
Memory
Disk
Network

Bt k ngun/ch loi no u c th s
dng lung c/ghi d liu.
81

Nhp xut d liu


c d liu
Open a Stream
While more Information
Read
Close the Stream
Ghi d liu
Open a Stream
While more Information
Write
Close the Stream
82

Lung d liu
Cc lung l nhng ng ng dn gi v
nhn thng tin trong cc chng trnh java.
Khi mt lung c hoc ghi , cc lung khc
b kho.
Nu li xy ra trong khi c hoc ghi lung,
mt ngoi l s kch hot.

Lung d liu
Gi java.io cung cp cc lp ci t lung
d liu.
Phn loi lung

84

Lung d liu
Lung Character c dng khi thao tc trn k t (16
bits) S dng lp Reader & Writer
Byte Streams are c dng khi thao tc d liu nh
phn (8 bits) S dng InputStream & OutputStream
Classes
Data Sinks
Files
Memory
Pipes

Processing
Buffering
Filtering
85

Cc lp lung d liu
Lp System.out.
Lp System.in.
Lp System.err.

Lung Byte

Lp InputStream
L lp tru tng
nh ngha cch nhn d liu
Cung cp s phng thc dng c v
cc lung d liu lm u vo.
Cc phng thc:
int read()
int read(byte[] buffer)
int read(byte[] buffer, int offset, int length)
int available( )
void close ( )
void reset( )
long skip( )

Lp InputStream
int read()
byte[] b = new byte[10];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) System.in.read();
}

Lp InputStream
int read()
public class StreamPrinter {
public static void main(String[] args) {
try {
while (true) {
int datum =
System.in.read( );
if (datum == -1) break;
System.out.println(datum);
}
} catch (IOException ex) {
System.err.println("Couldn't read from System.in!");
}
}
}

Lp InputStream
int read(byte[] buffer, int offset, int length)
try {
byte[] b = new byte[100];
int offset = 0;
while (offset < b.length) {
int bytesRead = System.in.read(b, offset, b.length - offset);
if (bytesRead == -1) break; // end of stream
offset += bytesRead;
}
}
catch (IOException ex) {
System.err.println("Couldn't read from System.in!");
}

Lp InputStream
int available()
try {
byte[] b = new byte[System.in.available( )];
System.in.read(b);
}
catch (IOException ex) {
System.err.println("Couldn't read from System.in!");
}

Lp InputStream
long skip()
try {
long bytesSkipped = 0;
long bytesToSkip = 80;
while (bytesSkipped < bytesToSkip) {
long n = in.skip(bytesToSkip - bytesSkipped);
if (n == -1) break;
bytesSkipped += n;
}
}
catch (IOException ex) { System.err.println(ex); }

Lp OutputStream
L lp tru tng.
nh ngha cch ghi d liu vo lung.
Cung cp tp cc phng thc tr gip.
trong vic to, ghi v x l cc lung xut.
Cc phng thc:

void write(int)
void write(byte[ ])
write(byte[ ], int, int)
void flush( )
void close( )

Lp OutputStream
void write(int i)
public class AsciiChart {
public static void main(String[] args) {
for (int i = 32; i < 127; i++) {
System.out.write(i);
// break line after every eight characters.
if (i % 8 == 7) System.out.write('\n');
else System.out.write('\t');
}
System.out.write('\n');
}
}

Lp OutputStream
void write(byte[] buff)
void write(byte[] buff, int offset, int length)
public class WriteBytes
public static void main(String[] args){
try{
String message = Hello World;
byte[] data = message.getBytes();
System.out.write(data);
catch(IOException e)
{
System.out.println(IO errors);
}
}
}

Lp OutputStream
public class StreamCopier {
public static void main(String[] args) {
try {
copy(System.in, System.out); }
catch (IOException ex) {
System.err.println(ex);
}
}
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) break;
out.write(buffer, 0, bytesRead);
}
}
}

Lp FileOutputStream
Cho php kt xut ghi ra mt lung
tp tin
Cc i tng cng to ra s dng mt
chui tn tp tin, tp tin, hay i tng
FileDescriptor nh mt tham s.
Lp ny np chng cc phng thc
ca lp OutputStream v cung cp
phng thc finalize( ) v getFD( )

S Dng FileOutputStream
byte[] originalData = new byte[10];
for (int i=0; i<originalData.length; i++)
{
originalData[i]=(byte)(Math.random()*128.0);
}
FileOutputStream fw=null;
try { fw = new FileOutputStream("io1.dat"); }
catch (IOException fe )
{ System.out.println(fe); }
for (int i=0; i<originalData.length; i++)
{
try { fw.write(originalData[i]); }
catch (IOException ioe)
{System.out.println(ioe); }
}
try { fw.close(); }
catch (IOException ioe)
{System.out.println(ioe); }

Lp FileInputStream
Cho php u vo c t mt tp tin
trong mt mu ca mt dng
Cc i tng c to ra s dng chui
tn tp tin, tp tin, i tng
FileDescriptor nh mt tham s.
Cc phng thc np chng ca lp
InputStream. n cung cp phng thc
finalize( ) v getFD( )

S Dng FileInputStream
byte data=0;
int bytesInFile=0;
FileInputStream fr = null;
try
{
fr = new FileInputStream("io1.dat");
bytesInFile = fr.available();
for (int i=0; i<bytesInFile; i++)
{
data=(byte)fr.read();
System.out.println("Read "+data);
}
fr.close();
}
catch (IOException ioe)
{
System.out.println("Problem with file");
}
Java I/O

ByteArrayInput
S dng cc m b nh
Lp ByteArrayInputStream
ByteArrayInputStream(byte[] buf)

To ra mt lung nhp t m b nh
mng cc byte.

Khng h tr cc phng thc mi


Cc phng thc np chng ca lp
InputStream, ging nh read(), skip(),
available() v reset().

Byte Array Output


s dng cc vng m b nh
Lp ByteArrayOutputStream
To ra mt lung kt xut trn mng byte
Cung cp cc kh nng b sung cho
mng kt xut tng trng nhm cha
ch cho d liu mi ghi vo.
Cng cung cp cc phng thc
chuyn i lung ti mng byte, hay i
tng String.

Phng thc ca lp
ByteArrayOutputStream :

ByteArrayOutputStream()
void reset( )
int size( )
byte[] toByteArray()
String toString()

B lc
Lc:
L kiu lung sa i cch iu qun mt lung
hin c.
v c bn c s dng thch ng cc lung
theo cc nhu cu ca chng trnh c th.
B lc nm gia lung c s v CT.
Thc hin mt s tin trnh t bit trn cc byte
c chuyn giao t u vo n kt xut.
C th phi hp thc hin mt dy cc tu
chn lc.

Lp FilterInputStream

L lp tru tng.
L cha ca tt c cc lp lung nhp lc.
Cung cp kh nng to ra mt lung t lung khc.
Mt lung c th c v cung cp cung cp di
dng kt xut cho lung khc.
duy tr mt dy cc i tng ca lp InputStream
Cho php to ra nhiu b lc kt xch (chained
filters
).

Lp FilterOutputStream
L
dng
b
tr
cho
lp
FilterInputStream.
L cha ca tt c cc lp lung kt xut.
Duy tr i tng ca lp
OutputStream nh l mt bin out.
D liu ghi ra lp ny c th sa i
thc hin cc thao tc lc, v sau
phn hi n i tng OutputStream.

Lung Lc

Vng m nhp/xut
Vng m:
L kho lu tr d liu.
C th cung cp d liu thay v quay tr li ngun d
liu gc ban u.
Java s dng vng m nhp v kt xut tm thi
lp cache d liu c c hoc ghi vo mt lung.
Trong khi thc hin vng m nhp:

S lng byte ln c c cng thi im, v lu


tr trong mt vng m nhp.
Khi chng trnh c lung nhp, cc byte nhp c
c vo vng m nhp.

Vng m nhp/xut (tt)


Trong trng hp vng m kt xut, mt
chng trnh ghi ra mt lung.
D liu kt xut c lu tr trong mt vng
m kt xut.
D liu c lu tr cho n khi vng m tr
nn y, hay lung kt xut c x trng.
Kt thc, vng m kt xut c chuyn gi
n ch ca lung xut.

Lp BufferedInputStream
T ng to ra v duy tr vng m h tr
vng m nhp.
bi lp BufferedInputStream l mt b m,
n c th p ng cho mt s cc i tng
nht nh ca lp InputStream.
Cng c th phi hp cc tp tin u vo
khc.
S dng vi bin trin khai vng m nhp.

Lp BufferedInputStream
(Contd)
nh ngha hai phng thc thit lp:

Mt cho php ch nh kch thc ca vng m nhp.


phng thc kia th khng.

C hai phng thc thit lp u tip nhn mt


i tng ca lp InputStream nh mt tham
s.
Np chng cc phng thc truy cp m
InputStream cung cp, v khng a vo bt k
phng thc mi no.

Lp BufferedOutputStream
Thc hin vng m kt xut theo cch
tng ng vi lp BufferedInputStream.
nh ngha hai phng thc thit lp. N cho
php chng ta n nh kch thc ca vng
m xut trong mt phng thc thit lp,
cng ging nh cung cp kch thc vng
m mc nh.
Np chng tt c phng thc ca lp
OutputStream v khng a vo bt k
phng thc no.

Giao din DataInput


c s dng c cc byte t lung nh
phn, v xy dng li d liu trong mt s
kiu d liu nguyn thu.
Cho php chng ta chuyn i d liu t t
khun dng UTF-8 c sa i Java n
dng chui
nh nghi s phng thc, bao gm cc
phng thc c cc kiu d liu nguyn
thu.

Nhng phng thc giao din


DataInput
boolean readBoolean( )

float readFloat( )

byte readByte( )

int readInt( )

char readChar( )

double readDouble

short readShort( )

String readUTF( )

long readLong( )

String readLine( )

Giao din DataOutput


c s dng xy dng li d liu mt s
kiu d liu nguyn thu vo trong dy cc
byte
Ghi cc byte d liu vo lung nh phn
Cho php chng ta chuyn i mt chui vo
khun dng UTF-8 c sa i Java v vit
n vo trong mt dy.
nh ngha mt s phng thc v tt c
phng thc kch hot IOException trong
trng hp li.

Cc phng thc giao din


DataOutput
void writeBoolean(boolean b)
void writeByte( int value)
void writeChar(int value)
void writeShort(int value)
void writeLong(long value)
void writeFloat(float value)
void writeInt(int value)
void writeDouble(double value)
void writeUTF(String value)

Mng byte sang int

public class ArrayCopy {


public static int[] byte2int(byte[]src) {
int dstLength = src.length >>> 2;
int[]dst = new int[dstLength];
for (int i=0; i<dstLength; i++) {
int j = i << 2;
int x = 0;
x += (src[j++] & 0xff) << 0;
x += (src[j++] & 0xff) << 8;
x += (src[j++] & 0xff) << 16;
x += (src[j++] & 0xff) << 24;
dst[i] = x;
}
return dst;
}
}

S Dng DataOutputStream
int[] originalData = new int[10];
for (int i=0; i<originalData.length; i++)
originalData[i]=(int)(Math.random()*1000.0);
FileOutputStream fos=null;
try { fos = new FileOutputStream("io2.dat"); }
catch (IOException fe )
{ System.out.println("Cant make new file"); }
DataOutputStream dos = new DataOutputStream(fos);
for (int i=0; i<originalData.length; i++)
{
try { dos.writeInt(originalData[i]); }
catch (IOException ioe)
{System.out.println("Cant write to file"); }
}

Lp Reader v Writer
L cc lp tru tng.
Chng nm ti nh ca h phn cp
lp, h tr vic c v ghi cc lung k
t unicode.

Lp Reader
Reader
CharArray
Reader
InputStream
Reader

File
Reader

Piped
Reader

String
Reader

Filter
Reader

Buffered
Reader

Pushback
Reader

LineNumber
Reader

Lp Reader
H tr cc phng thc sau:

int read( )
int read(char[] data)
int read(char[] data, int offset, int len)
void reset( )
long skip( )
void close( )
boolean ready( )

Lp Writer
Writer
CharArray
Writer

Filter
Writer
OutputStream
Writer

File
Writer

String
Writer
Print
Writer

Piped
Writer
Buffered
Writer

Lp Writer
H tr cc phng thc sau :

void write( int ch)


void write(char[] text)
void write(String str)
void write(String str, int offset, int len)
void flush( )
void close( )

c Tp Tin Vn Bn
import java.io.*;
public class FileRead
{
public static void main(String[] args) throws IOException
{
//all the following, up to the definition of the reader, are in
//the class java.io.File, which contains a number of methods
//related to the file attributes and the directory it resides in.
String fileName = args[0];

// args[0] for file name

//the next statement creates a reader for the file


BufferedReader dat = new BufferedReader(new FileReader(fileName));
System.out.println("DATA FROM THE FILE: " + fileName);

//If there is no more data in the file, readLine returns null


String line = dat.readLine();
while (line != null)
{
System.out.println(line);
line = dat.readLine();
}
System.out.println("END OF FILE REACHED");
dat.close();
}

125

CIE OOP

c Tp Tin
import java.io.*;
public class IntFileRead
{
public static void main(String[] args) throws IOException
{
File dataf = new File ("data.txt");
int number;
//Create a reader for the file
FileReader fdat = new FileReader(dataf);
BufferedReader dat = new BufferedReader(fdat);
System.out.println("DATA FROM THE FILE:");
String line = dat.readLine();
while (line != null)
{
number=Integer.parseInt(line);
System.out.println(number);
line = dat.readLine();
}
System.out.println("END OF FILE REACHED");
dat.close();
}//end main
}//end IntFileRead
126

CIE OOP

Lp PrinterWriter
Thc hin mt kt xut.
Lp ny c phng thc b sung , tr gip in cc
kiu d liu c bn .
Lp PrintWriter thay th lp PrintStream
Thc t ci thin lp PrintStream; lp ny dng
mt du tch dng ph thuc nn tng im cc
dng thay v k t \n.
Cung cp phn h tr cho cc k t unicode so
vi PrintStream.
Cc phng thc:
checkError( )
setError( )

Ghi Xung Tp Tin


import java.io.*;
public class TextFileWrite
{
public static void main(String[] args) throws IOException
{
//for this example, set up data we want to write as a four element array of strings
String [] song = new String [4];
song[0]="Mary had a little lamb";
song[1]="Its fleece was white as snow";
song[2]="And everywhere that Mary went";
song[3]="The lamb was sure to go";
//set up the output file to be written to
String outFileName = args[0];
//using PrintWriter allows us to use the print and println commands for files
File outData = new File(outFileName);
PrintWriter outDat = new PrintWriter(new FileWriter(outData));
//Now write the data .....
for (int line=0; line<song.length; line++)
outDat.println(song[line]);
System.out.println("DATA WRITTEN ON OUTPUT FILE: "+ outFileName);
outDat.close();
128

}
}

CIE OOP

Lp RandomAccessFile
Cung cp kh nng thc hin I/O theo cc v
tr c th bn trong mt tp tin.
d liu c th c hoc ghi ngu nhin
nhng v tr bn trong tp tin thay vi mt kho
lu tr thng tin lin tc.
phng thc seek( ) h tr truy cp ngu
nhin.
Thc hin c u vo v u ra d liu.
H tr cc cp php c v ghi tp tin c
bn.
K tha cc phng thc t cc lp
DataInput v DataOutput

Cc phng thc ca lp
RandomAccessFile
RandomAccessFile(String fn,String mode)

r, rw, ..
seek( )
getFilePointer( )
length( )
readBoolean()
.
writeBoolean()
..

RandomAccessFile example
RandomAccessFile rf = new
RandomAccessFile(doubles.dat,rw);
// read third double: go to 2 * 8 (size of one)
rf.seek(8*2);
double x = rf.readDouble();
// overwrite first double value
rf.seek(0);
rf.writeDouble(x);
rf.close();

Bi tp

Serialization
Thao tc c v ghi cc i tng
Serialization cng c h tr trong cc
ngn ng khc nhng rt kh thc hin
Java gip vic thc hin serializtion rt d
dng

133

K c th serializability
i tng c serialized nu:
Lp l public
Lp phi implement Serializable
Lp phi c no-argument constructor

134

Writing objects to a file


ObjectOutputStream objectOut =
new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(fileName)));
objectOut.writeObject(serializableObject);
objectOut.close( );
135

Reading objects from a file


ObjectInputStream objectIn =
new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
myObject = (itsType)objectIn.readObject( );
objectIn.close( );
136

You might also like