Java - Chương 4: Nhập xuất

Định dạng nhập/xuất Khái niệm luồng Các luồng byte Các luồng ký tự File truy cập ngẫu nhiên Luồng nhập/xuất đối tượng. Nhập/xuất với Scanner. Nhập/xuất với JOptionPane

pptx56 trang | Chia sẻ: thuychi16 | Lượt xem: 776 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Java - Chương 4: Nhập xuất, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Chương 4.1Nhập xuấtChương 4.1: Nhập xuấtĐịnh dạng nhập/xuấtKhái niệm luồngCác luồng byteCác luồng ký tựFile truy cập ngẫu nhiênLuồng nhập/xuất đối tượng.Nhập/xuất với Scanner.Nhập/xuất với JOptionPaneĐịnh dạng nhập xuấtSử dụng hàm printf() và println() để định dạng kiểu dữ liệu ở console.Mã định dạngMô tả%dKết quả định dạng như một số nguyên thập phân%fKết quả định dạng như là một số thực%oKết quả định dạng như là một số Octal (Cơ số 8)%eKết quả định dạng như là một số thập phân trong kiểu số khoa học%nKết quả được hiển thị trong một dòng mớiĐịnh dạng nhập xuấtVí dụ: Thực hiện đoạn chương trình sau:public static void main(String[] args){ float i = 8; float j = 3; System.out.println(“Ket qua cua i/j la: “ + i/j); System.out.printf(“Ket qua cua i/j la %.2f”, i/j);}Kết quả:Luồng (Stream)Luồng là một “dòng chảy” của dữ liệu được gắn với các thiết bị vào ra.Hai loại luồng:Luồng nhập: Gắn với các thiết bị nhập như bàn phím, máy scan, file...Luồng xuất: Gắn với các thiết bị xuất như màn hình, máy in, file,Các luồng cơ bảnByte streamsHỗ trợ việc xuất nhập dữ liệu trên byte, thường được dùng khi đọc ghi dữ liệu nhị phân.InputStream: Luồng nhập byte cơ bảnOutputStream: Luồng xuất byte cơ bảnCharacter streamsCho các ký tự UnicodeReader: Luồng nhập ký tự cơ bảnWriter: Luồng xuất ký tự cơ bảnBiến /Đối tượngDòng nhập byte vật lýXử lý từng byte mộtDòng nhập ký tựXử lý theo đơn vị 2 byteDòng xuất byte vật lýXử lý từng byte mộtDòng xuất ký tựXử lý theo đơn vị 2 byteLớp trừu tượng trên cùngjava.io.InputStreamLớp trừu tượng trên cùngjava.io.OutputStreamLớp trừu tượng trên cùngjava.io.ReaderLớp trừu tượng trên cùngjava.io.WriterCác lớp luồng nằm trong gói java.ioCác luồng cơ bảnLuồng byteinput stream: sử dụng để đọc dữ liệu.output stream: sử dụng để ghi dữ liệu.Cây thừa kế InputStreamCác phương thức của InputStreamint available( )Trả về số luợng bytes có thể đọc được từ luồng nhậpvoid close( )Đóng luồng nhập và giải phóng tài nguyên hệ thống gắn với luồng. Không thành công sẽ ném ra một lỗi IOExceptionvoid mark(int numBytes)Đánh dấu ở vị trí hiện tại trong luồng nhậpboolean markSupported( )Kiểm tra xem luồng nhập có hỗ trợ phương thức mark() và reset() không.int read( )Đọc byte tiếp theo từ luồng nhậpint read(byte buffer[ ])Đọc buffer.length bytes và lưu vào trong vùng nhớ buffer. Kết quả trả về số bytes thật sự đọc đượcint read(byte buffer[ ], int offset, int numBytes)Đọc numBytes bytes bắt đầu từ địa chỉ offset và lưu vào trong vùng nhớ buffer. Kết quả trả về số bytes thật sự đọc đượcvoid reset( )Nhảy con trỏ đến vị trí được xác định bởi việc gọi hàm mark() lần sau cùng.long skip(long numBytes)Nhảy qua numBytes dữ liệu từ luồng nhậpCây thừa kế OutputStreamCác phương thức của OutputStreamvoid close( )Đóng luồng xuất và giải phóng tài nguyên hệ thống gắn với luồng. Không thành công sẽ ném ra một lỗi IOExceptionvoid flush( )Ép dữ liệu từ bộ đệm phải ghi ngay xuống luồng (nếu có)void write(int b)Ghi byte dữ liệu chỉ định xuống luồngvoid write(byte buffer[ ])Ghi buffer.length bytes dữ liệu từ mảng chỉ định xuống luồngvoid write(byte buffer[ ], intoffset, int numBytes)Ghi numBytes bytes dữ liệu từ vị trí offset của mảng chỉ định buffer xuống luồng13Mở một file để đọc dữ liệu FileInputStream(String fileName) throws FileNotFoundException Nếu file không tồn tại: thì ném ra FileNotFoundExceptionĐọc dữ liệu: dùng phương thức read() int read( ) throws IOException: đọc từng byte từ file và trả về giá trị của byte đọc được. Trả về -1 khi hết file, và ném ra IOException khi có lỗi đọc.Đóng file: dùng phương thức close() void close( ) throws IOException: sau khi làm việc xong cần đóng file để giải phóng tài nguyên hệ thống đã cấp phát cho file.Đọc dữ liệu từ fileMở một file để ghi dữ liệu FileOutputStream(String fileName) throws FileNotFoundException Nếu file không tạo được: thì ném ra FileNotFoundExceptionGhi dữ liệu xuống: dùng phương thức write() void write(int byteval) throws IOException: ghi một byte xác định bởi tham số byteval xuống file, và ném ra IOException khi có lỗi ghi.Đóng file: dùng phương thức close() void close( ) throws IOException: sau khi làm việc xong cần đóng file để giải phóng tài nguyên hệ thống đã cấp phát cho file.Ghi dữ liệu từ fileSử dụng FileInputStream & FileOutputStream//Ví dụ chép dữ liệu từ file doc.txt sang ghi.txtimport java.io.*;public class DocFile1 { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(“d:/doc.txt"); out = new FileOutputStream(“d:/ghi.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }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"); } }}Ví dụ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"); } }}Ví dụLuồng ký tự (Character Stream)Java platform lưu trữ những giá trị ký tự theo dạng UnicodeTất cả các lớp character stream được kế thừa từ Reader và Writer Có các lớp character stream: FileReader FileWriter19Để đọc và ghi những giá trị nhị phân của các kiểu dữ liệu trong java, chúng ta sử dụng:DataInputStreamDataOutputStream.Đọc ghi dữ liệu nhị phân20void writeBoolean(boolean val)Ghi xuống luồng một giá trị boolean được xác định bởi val.void writeByte (int val)Ghi xuống luồng một byte được xác định bởi val.void writeChar (int val)Ghi xuống luồng một Char được xác định bởi val.void writeDouble(double val)Ghi xuống luồng một giá trị Double được xác định bởi val.void writeFloat (float val)Ghi xuống luồng một giá trị float được xác định bởi val.void writeInt (int val)Ghi xuống luồng một giá trị int được xác định bởi val.void writeLong (long val)Ghi xuống luồng một giá trị long được xác định bởi val.void writeShort (int val)Ghi xuống luồng một giá trị short được xác định bởi val.Contructor: DataOutputStream(OutputStream outputStream)OutputStream: là luồng xuất dữ liệu. Để ghi dữ liệu ra file thì đối tượng outputStream có thể là FileOutputStream.Đọc ghi dữ liệu nhị phân21boolean readBoolean( )Đọc một giá trị booleanByte readByte( )Đọc một bytechar readChar( )Đọc một Chardouble readDouble( )Đọc một giá trị Doublefloat readFloat( )Đọc một giá trị floatint readInt( )Đọc một giá trị intlong readLong( )Đọc một giá trị longshort readShort( )Đọc một giá trị shortContructor: DataInputStream(InputStream inputStream)InputStream: là luồng nhập dữ liệu. Để đọ dữ liệu từ file thì đối tượng InputStream có thể là FileInputStream.Đọc ghi dữ liệu nhị phân22import java.io.*;class RWData{ public static void main(String args[]) throws IOException{ DataOutputStream dataOut; DataInputStream dataIn; int i = 10; double d = 1023.56; boolean b = true; try { dataOut = new DataOutputStream(new FileOutputStream("D:\\testdata")); }catch(IOException exc) { System.out.println("Cannot open file."); return; } try { System.out.println("Writing " + i); dataOut.writeInt(i); System.out.println("Writing " + d); dataOut.writeDouble(d); System.out.println("Writing " + b); Đọc ghi dữ liệu nhị phân23 dataOut.writeBoolean(b); System.out.println("Writing " + 12.2 * 7.4); dataOut.writeDouble(12.2 * 7.4); } catch(IOException exc) { System.out.println("Write error."); } dataOut.close(); System.out.println(); // Now, read them back. try { dataIn = new DataInputStream( new FileInputStream("D:\\testdata")); } catch(IOException exc) { System.out.println("Cannot open file."); return; }Đọc ghi dữ liệu nhị phân24 try { i = dataIn.readInt(); System.out.println("Reading " + i); d = dataIn.readDouble(); System.out.println("Reading " + d); b = dataIn.readBoolean(); System.out.println("Reading " + b); d = dataIn.readDouble(); System.out.println("Reading " + d); } catch(IOException exc) { System.out.println("Read error."); } dataIn.close(); } }Đọc ghi dữ liệu nhị phânCây kế thừa của Reader và WriterCác phương thức của ReaderCác phương thức của WriterSử dụng FileReader & FileWriter//Ví dụ chép dữ liệu từ file doc.txt sang ghi.txtimport java.io.*;public class DocFile2 { public static void main(String[] args) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("d:/doc.txt"); out = new FileWriter("d:/ghi.txt"); int c; while ((c = in.read()) != -1){ out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }}Sử dụng BufferedReader và BufferedWriterMột I/O không có bộ đệm có nghĩa là mỗi yêu cầu đọc hoặc ghi được xử lý trực tiếp bởi HĐH.Điều này làm chương trình kém hiệu quả, vì mỗi yêu cầu thường phải truy xuất đĩa, hoạt động mạng-> tốn thời gian.Java platform thực thi luồng I/O có bộ đệm Buffered input stream: Đọc dữ liệu từ vùng nhớ như là bộ đệmAPI input được gọi chỉ khi bộ đệm rỗng. Buffered output stream: Ghi dữ liệu xuống bộ đệm.API output chỉ được gọi khi buffer đầy.//Ví dụ chép dữ liệu từ file doc.txt sang ghi.txtimport java.io.*;public class DocFile3 { public static void main(String[] args) throws IOException { BufferedReader in = null; BufferedWriter out = null; try { in = new BufferedReader(new FileReader("d:/doc.txt")); out = new BufferedWriter(new FileWriter("d:/ghi.txt")); int c; while ((c = in.read()) != -1) { out.write(c);} } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } }}}Sử dụng BufferedReader và BufferedWriterChuẩn Buffered StreamsTất cả các chương trình viết bằng java luôn tự động import gói java.lang. Gói này có định nghĩa lớp System, nó có ba biến luồng được định nghĩa trước là in, out và err, chúng là các fields được khai báo static trong lớp System.System.out: luồng xuất chuẩn, mặc định là console. System.out là một đối tượng kiểu PrintStream.System.in: luồng nhập chuẩn, mặc định là bàn phím. System.in là một đối tượng kiểu InputStream.System.err: luồng lỗi chuẩn, mặc định cũng là console. System.err cũng là một đối tượng kiểu PrintStream giống System.out.32//nhập liệu sử dụng phương thức System.in.read() import java.io.*;class ReadBytes{ public static void main(String args[]) throws IOException { byte data[] = new byte[100]; System.out.print("Enter some characters."); System.in.read(data); System.out.print("You entered: "); for(int i=0; i chuỗi int iNumber = Integer.parseInt(siNumber); //chuyển sang định dạng số System.out.print("Nhap mot so thuc:"); String sfNumber = inStream.readLine(); float fNumber = Float.parseFloat(sfNumber); System.out.println("So nguyen:" + iNumber); System.out.println("So thuc:" + fNumber); }}Ví dụimport java.io.*;public class OutStream1 {public static void main(String[] args) { OutputStream os = System.out; //Monitor try{ String str = "The example of OutputStream\n"; byte b[] = str.getBytes(); os.write(b); } catch(IOException ie){ System.out.println("Error: " + ie); } }}Hai hạn chế của việc xử lý file thông qua luồngKhông thể đọc và ghi file cùng một lúcTruy nhập file mang tính tuần tựJava hỗ trợ việc truy nhập và xử lý file một cách tự do thông qua lớp RandomAccessFile.File truy nhập ngẫu nhiênCác phương thức cơ bảnRandomAccessFile(String name, String mode) // trong đó mode có thể là “r”, “w”, “rw”int readInt(); // đọc số nguyênvoid writeInt(int v); // ghi số nguyênlong readLong(); // đọc số longvoid writeLong(long v); // ghi số longvoid seek(long pos); // di chuyển vị trí con trỏ filelong getFilePointer(); // lấy vị trí của con trỏ filelong length(); // lấy kích cỡ của filevoid close(); // đóng file...File truy nhập ngẫu nhiêntry{ 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()); f.seek(0); System.out.println(f.readBoolean()); f.close();} catch (IOException e) { System.out.println(“Error IO file”);}Sử dụng RandomAccessFileLuồng nhập/xuất đối tượng//ghi lại tên và ngày sinhtry{ 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”);}Ví dụVí dụ//đọc tên và ngày sinhtry{ 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”);}// file Student.javapublic 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; }}Đọc ghi đối tượng tự tạo// file WriteMyObject.javaimport 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”); }Đọc ghi đối tượng tự tạo try { 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”); } }}Đọc ghi đối tượng tự tạoĐối tượng có thể cài đặt 2 phương thức sau để thực hiện đọc/ghi theo cách riêng của mình.private void writeObject(ObjectOutputStream out) throws IOException private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundExceptionĐọc ghi đối tượng tự tạoĐọc ghi đối tượng tự tạoTóm tắt về xử lý fileNhập dữ liệu sử dụng lớp ScannerScanner có nhiều tiến bộ hơn BufferReader.Phân loại được dữ liệu mà người dùng nhập vào, có thể đọc kiểu int, float, double,BufferedReader in1 = new BufferedReader(new InputStreamReader(System.in));System.out.println(“Nhập vào một số nguyên: ");String siNumber = in1.readLine(); //đọc dữ liệu -> chuỗiint iNumber = Integer.parseInt(siNumber); //chuyển sang định dạng số.Scanner in1=new Scanner(System.in);System.out.println(“Nhập vào một số nguyên: ");age= in1.nextInt(); //nhận trực tiếp kiểu int Một số phương thức của lớp ScannernextInt() : trả về kiểu int nextFloat() : trả về kiểu float nextBoolean() : trả về kiểu boolean nextByte() : trả về kiểu byte nextLine() : trả về kiểu String.Nhập dữ liệu sử dụng lớp Scannerimport java.util.Scanner;public class GetInputFromKeyboard { public static void main(String[] args) { //Tạo một đối tượng Scanner Scanner in1=new Scanner(System.in); String name = ""; int age; System.out.println("Hãy nhập tên: "); name = in1.nextLine(); System.out.println("Hãy nhập tuổi: "); age= in1.nextInt(); System.out.println("Name is " + name +"!"); System.out.println("Age is " + age +"!"); }}Nhập xuất với JOptionPaneJOptionPane là một lớp kế thừa từ lớp JComponent.Khi biên dịch program thì nó sẽ hiện lên một dialog box cho phép nhập dữ liệu.Một số phương thức:showConfirmDialog(): Hiển thị một câu hỏi lựa chọn giống như yes no cancelshowInputDialog(): Hiển thị box nhậpshowMessageDialog(): Báo cho người dùng một sự kiện vừa xảy ra.Nhập xuất với JOptionPaneimport javax.swing.JOptionPane;public class InputFromKeyboardJOptionPane { public static void main(String[] args) { String name = ""; name=JOptionPane.showInputDialog(“Nhập vào tên của bạn:"); String msg = "Hello " + name + "!"; JOptionPane.showMessageDialog(null, msg); System.out.println("Name is:"+msg); }}Các thao tác với tập tin và thư mụcFile (java.io.File): giúp thao tác với tập tin và thư mụcMột số hàm của lớp này như:isFile kiểm tra đúng là tập tin hay không.isDirectory kiểm tra phải thư mụcexists kiểm tra tập tin hoặc thư mục có tồn tại.canRead kiểm tra quyền đọc của tập tin hoặc thư mụccanWrite kiểm tra có quyền ghi khôngsetReadable cài đặt quyền đọc cho tập tin hoặc thư mụcsetWritable cài đặt quyền ghi cho tập tin hoặc thư mụcmkdir tạo một thư mục tại đường dẫn đórenameTo đổi tên tập tin hay thư mụcdelete xóa tập tin hoặc thư mụccreateNewFile tạo tập tinCác thao tác với tập tin và thư mụcĐọc thư mục d:/eclipse rồi in ra kết quả đường dẫn của các fileimport java.io.File;public class CreateDirectoryExample { public static void main(String[] args) { File file = new File("d:/angiang/longxuyen"); if (!file.exists()) { if (file.mkdir()) { System.out.println("Directoryreated!"); } else { System.out.println("Failedreate directory!"); } } } }Các thao tác với tập tin và thư mụcimport java.io.File;public class CreateDirectory1 { public static void main(String[] args) { File myDocumentFolder = new File("d:/eclipse"); if(myDocumentFolder.exists() && myDocumentFolder.isDirectory() && myDocumentFolder.canRead()) { File[] files = myDocumentFolder.listFiles(); for(File f : files) { System.out.println(f); } } }}Bài tập tại lớpBài 1: Viết chương trình đếm xem trong một file văn bản cho trước có bao nhiêu câu. Biết rằng các câu kết thúc bởi dấu chấm.Bài 2: Viết chương trình tạo file ghi 100 số Fibonacci đầu tiên. Viết chương trình thứ hai để đọc và hiển thị dữ liệu từ file này.
Tài liệu liên quan