Binary I/O
Outline Text I/O Chap 9. WriteData Chap 9. ReadData Binary I/O Text I/O vs Binary I/O Binary I/O Classes Using DataInputStream/DataOutputStream Copy File [Sample code] TestFileStream.java 、 TestDataStream.java 、 Copy.java
Text I/O Write: // Write text to a file named temp.txt PrintWriter output = new PrintWriter(“temp.txt”); // Invoke the print method from the object to write a string into a file. Output.print(“Java 101”) // Closed the file. Output.close();
Read: // Using Scanner class Scanner input = new Scanner(new File(“temp.txt”)); System.out.println(input.nextLine()); // input.nextLine() 回傳 “Java 101”
Chap 9. WriteData
Chap 9. ReadData
Binary I/O All files are store in binary format. No need to encode and decode.
Binary I/O Program Input object created from an input class Output object created from an output class File 01011… …1011 Input stream output stream The program receives data and send data
Text I/O vs Binary I/O Text I/O program The Unicode of the character e.g.,”199” The encoding of the character is stored in the file Encoding Decoding Binary I/O program A byte is read/written e.g.,”199” The encoding of the character is stored in the file ※ Text I/O requires encoding and decoding, whereas binary I/O does not ※ 199 = 12 x 0xC7 1
Binary I/O Classes 課本 P.676
程式範例 : TestFileStream.java
Using DataInputStream/DataOutputStream Data streams constructors: public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream) Create data streams: DataInputStream input = new DataInputStream(new FileInputStream(“in.dat”)); DataOutputStream output = new DataOutputStream(new FileOutputStream(“out.dat”));
程式範例 : TestDataStream.java
BufferedInputStream/BufferedOutputStream BufferedInputStream/BufferedOutputStream can be used to speed up input and output by reducing number of reads and writes. All the methods in BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes
可在 TestDataStream.java 的第 8 行及第 22 行加入 : DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("temp.dat"))); DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream("temp.dat")));
Copy File 程式範例 : Copy.java ※ Java Copy source target
程式練習 : Programming Exercises 19.2