Professional Documents
Culture Documents
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;
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;
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
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
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
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
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)
{
:
}
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)
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
java.lang.NumberFormatExcept
}
ion: For input string:
exception"
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
V d:
NullPointerException,IndexOutOfBoundsException,
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
(when i = 4)
ArithmeticException
(Division by zero)
Lin quan n 1 vn c th
Khi mt phng thc c gi thi hnh
V d:
IOException
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.
}
f.method();
catch
{
}
finally
{
}
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
}
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.*;
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
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);
}
}
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
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)
{
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
Ly ng dn ca tp tin
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
CIE OOP
80
Bt k ngun/ch loi no u c th s
dng lung c/ghi d liu.
81
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.
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:
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:
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.
float readFloat( )
byte readByte( )
int readInt( )
char readChar( )
double readDouble
short readShort( )
String readUTF( )
long readLong( )
String readLine( )
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 :
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];
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( )
}
}
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