Upload
hotkutepro
View
4
Download
0
Embed Size (px)
DESCRIPTION
Luồng trong java
Citation preview
Chng 3LUNG D LIU
Ni dungX l bit lLung d liuThao tc trn tp tin
Exception HandlingX l mi s dng c ch bit l trong Java
Cc cch x l liS dng cc mnh iu kin kt hp vi cc gi tr c.S dng c ch x l bit l.
V d: Lp Inventorypublic 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/cstore.addToInventory (int amt) if (temp > MAX) return false;reference2.method2 () if (store.addToInventory(amt) == false) return false;reference1.method1 () if (reference2.method2() == false) return false;
Cc vn i vi cch tip cn iu kin/cstore.addToInventory (int amt) if (temp > MAX) return false;reference2.method2 () if (store.addToInventory(amt) == false) return false;reference1.method1 () if (reference2.method2() == false) return false;
Cc vn i vi cch tip cn iu kin/cstore.addToInventory (int amt) if (temp > MAX) return false;reference2.method2 () if (store.addToInventory(amt) == false) return false;reference1.method1 () if (reference2.method2() == false) return false;
Cc vn i vi cch tip cn iu kin/cstore.addToInventory (int amt) if (temp > MAX) return false;reference.method2 () if (store.addToInventory(amt) == false) return false;reference1.method1 () if (reference2.method2() == false) return false;
Cc cch x l liS dng cc mnh iu kin kt hp vi cc gi tr c.S dng c ch x l bit l.
X l bit lC 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 phmimport 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: "); s = stringInput.readLine(); System.out.println("You typed in..." + s); num = Integer.parseInt (s); System.out.println("Converted to an integer..." + num); }
Lp BufferedReaderhttp://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); num = Integer.parseInt (s); System.out.println("Converted to an integer..." + num); }
Lp Integerhttp://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 lInteger.parseInt (String s){ : :}Driver.main ()try{ num = Integer.parseInt (s);} :catch (NumberFormatException e){ :}
C ch x l bit lInteger.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 lInteger.parseInt (String s){ }Driver.main ()try{ num = Integer.parseInt (s);} :catch (NumberFormatException e){ :}NumberFormatException e = new NumberFormatException ();
C ch x l bit lInteger.parseInt (String s){ }Driver.main ()try{ num = Integer.parseInt (s);} :catch (NumberFormatException e){ :}NumberFormatException e = new NumberFormatException ();
C ch x l bit lInteger.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();} }}
Cc loi bit lBit l khng cn kim traBit l phi kim tra
c im ca bit l khng cn kim traTrnh bin dch khng yu cu phi bt cc bit l khi n xy ra.Khng cn khi try-catchCc 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 sotX 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
Bit l khng cn kim tra: :ArrayIndexOutOfBoundsException int [] arr = null; arr[0] = 1;
arr = new int [4]; int i; for (i = 0; i
Bit l khng cn kim tra: : ArithmeticExceptions int [] arr = null; arr[0] = 1;
arr = new int [4]; int i; for (i = 0; i
Bit l cn phi kim traPhi x l khi bit l c kh nng xy raPhi s dng khi try-catchLin quan n 1 vn c thKhi 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 { 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 finallyL 1 mnh khng bt buc trong khi try-catch-finally.Dng t khi lnh s c thi hnh bt k bit l c xay ra hay khng.
Mnh finally: c bit ltry{ f.method();}catch{}finally{}Foo.method (){
}
Mnh finally: c bit ltry{ f.method();}catch{}finally{}f.method (){
}2) Bit l c to ra
Mnh finally: khng c bit ltry{ f.method();}catch{}finally{}f.method (){
}2) Phng thc thi hnh bnh thng
Try-Catch-Finally: V dclass Driver{ public static void main (String [] args) { TCFExample eg = new TCFExample (); eg.method(); }}
Try-Catch-Finally: V dpublic 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(""); return; } }}
Hm c gi khng th x l bit lmain ()Exception thrown!
Hm c gi khng th x l bit limport 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 lclass 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 lclass 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 lclass 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 lclass Driver{ public static void main (String [] args) throws IOException, NumberFormatException { TCExample eg = new TCExample (); eg.method(); }}
To ra kiu bit l miThrowableErrorVirtualMachineErrorOutOfMemoryErrorExceptionIOExceptionRunTimeException???Excerpt from Big Java by C. Horstmann p. 562
Lp ExceptionExceptionIOExceptionClassNotFoundExceptionCloneNotFoundExceptionEOFExceptionFileNotFoundExceptionMalformedURLExceptionUnknownHostException
To bit l miclass Driver{ public static void main (String [] argv) { Inventory chinookInventory = new Inventory (); CommandProcessor userInterface = new CommandProcessor (chinookInventory); userInterface.startProcessingInput (); }}
To bit l mipublic 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 Inventorypublic 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 InventoryOverMaxExceptionpublic class InventoryOverMaxException extends Exception{ public InventoryOverMaxException () { super (); }
public InventoryOverMaxException (String s) { super (s); }}
Lp InventoryBelowMinExceptionpublic class InventoryBelowMinException extends Exception{ public InventoryBelowMinException () { super(); }
public InventoryBelowMinException (String s) { super(s); }}
Nhc li tha kC th thay th mt i tng ca lp con cho 1 i tng ca lp cha (ngc li khng ng).
Cy tha k ca lp IOExceptions
Tha k v vn bt bit lKhi 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 ltry{
}catch (IOException e){
}catch (EOFException e){
} try{
}catch (EOFException e){
} catch (IOException e){
}ngSai
Qun L Tp Tin & Th Mcjava.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 FileCc Constructor: To i tng File t ng dn tuyt ipublic File(Stringpathname) v d: File f = new File(C:\\Java\\vd1.java);To i tng File t tn ng dn v tn tp tin tch bitpublic File(Stringparent, Stringchild)v d: File f = new File(C:\\Java, vd1.java);To i tng File t mt i tng File khcpublic File(Fileparent, Stringchild)v d: File dir = new File (C:\\Java);File f = new File(dir, vd1.java);
X l th mc Lp FileMt s phng thc thng gp ca lp File
public String getName()Ly tn ca i tng Filepublic String getPath()Ly ng dn ca tp tinpublic 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.
*CIE OOPNhp/xut d liuLp System c: in, out
System.out l 1 th hin ca lp PrintStream.
PrintStream c phng thc print, println ghi d liu xung lung.YourProgramFile(s)AnotherProgramInputStreamOutputStreamPrintStreamOther DevicesNhp xut d liu trong Java da trn m hnh lung d liu
*Nhp xut d liuD liu c th n t bt k ngun no v xut ra bt k ni noMemoryDiskNetwork
Bt k ngun/ch loi no u c th s dng lung c/ghi d liu.
*Nhp xut d liu c d liuOpen a Stream While more InformationReadClose the StreamGhi d liuOpen a Stream While more InformationWriteClose the Stream
Lung d liuCc 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 liuGi java.io cung cp cc lp ci t lung d liu.Phn loi lung
*Lung d liuLung 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 FilesMemoryPipes
ProcessingBufferingFiltering
Cc lp lung d liuLp System.out. Lp System.in.Lp System.err.
Lung Byte
Lp InputStream L lp tru tngnh ngha cch nhn d liuCung 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 InputStreamint read()
byte[] b = new byte[10]; for (int i = 0; i < b.length; i++) { b[i] = (byte) System.in.read(); }
Lp InputStreamint 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 InputStreamint 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 InputStreamint 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 InputStreamlong 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 OutputStreamvoid 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 OutputStreamvoid write(byte[] buff)void write(byte[] buff, int offset, int length)public class WriteBytespublic 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 OutputStreampublic 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 FileOutputStreamCho php kt xut ghi ra mt lung tp tinCc 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( )
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( )
ByteArrayInputS dng cc m b nhLp ByteArrayInputStreamByteArrayInputStream(byte[] buf)To ra mt lung nhp t m b nh mng cc byte.Khng h tr cc phng thc miCc phng thc np chng ca lp InputStream, ging nh read(), skip(), available() v reset().
Byte Array Outputs dng cc vng m b nhLp ByteArrayOutputStreamTo ra mt lung kt xut trn mng byteCung 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 lcLc: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 FilterInputStreamL 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 FilterOutputStreamL 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/xutVng 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 BufferedOutputStreamThc 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 chuinh nghi s phng thc, bao gm cc phng thc c cc kiu d liu nguyn thu.
Nhng phng thc giao din DataInputboolean readBoolean( ) byte readByte( ) char readChar( )short readShort( ) long readLong( )
float readFloat( )int readInt( ) double readDouble( ) String readUTF( ) String readLine( )
Giao din DataOutput c s dng xy dng li d liu mt s kiu d liu nguyn thu vo trong dy cc byteGhi cc byte d liu vo lung nh phnCho 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 DataOutputvoid 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)
Lp Reader v WriterL 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 ReaderReaderLineNumberReaderPushbackReaderInputStreamReaderCharArrayReaderFilterReaderBufferedReaderStringReaderPipedReaderFileReader
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 WriterWriterPrintWriterFileWriterBufferedWriterOutputStreamWriterPipedWriterFilterWriterCharArrayWriterStringWriter
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( )
*CIE OOPc Tp Tin Vn Bn
public class FileRead { public static void main(String[] args) { //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 System.out.println("DATA FROM THE FILE: " + fileName);
System.out.println("END OF FILE REACHED"); } }throws IOExceptionBufferedReader dat = new BufferedReader(new FileReader(fileName));
String line = dat.readLine(); while (line != null) { System.out.println(line); line = dat.readLine(); } //If there is no more data in the file, readLine returns nulldat.close();import java.io.*;
*CIE OOPc Tp Tinimport 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
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 PrintStreamThc 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 OOPGhi Xung Tp Tinimport 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
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 RandomAccessFileRandomAccessFile(String fn,String mode)r, rw, ..seek( )getFilePointer( )length( )readBoolean().writeBoolean()..
RandomAccessFile exampleRandomAccessFile 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 valuerf.seek(0);rf.writeDouble(x);rf.close();
Bi tp
*SerializationThao tc c v ghi cc i tngSerialization cng c h tr trong cc ngn ng khc nhng rt kh thc hinJava gip vic thc hin serializtion rt d dng
*K c th serializabilityi tng c serialized nu:Lp l publicLp phi implement SerializableLp phi c no-argument constructor
*Writing objects to a fileObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(fileName))); objectOut.writeObject(serializableObject); objectOut.close( );
*Reading objects from a fileObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream( new FileInputStream(fileName))); myObject = (itsType)objectIn.readObject( ); objectIn.close( );
Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling*Java exception handling***********