JavaCh 19 Binary IO 2011 05 06 Outline
Java@Ch 19. Binary I/O 2011. 05. 06
Outline • • Text I/O Chap 9. Write. Data Chap 9. Read. Data Binary I/O Text I/O vs Binary I/O Classes Using Data. Input. Stream/Data. Output. Stream Copy File [Sample code] Test. File. Stream. java 、 Test. Data. Stream. java 、Copy. java
Text I/O • Write: // Write text to a file named temp. txt Print. Writer output = new Print. Writer(“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. next. Line()); // input. next. Line() 回傳“Java 101”
Chap 9. Write. Data
Chap 9. Read. Data
Binary I/O • All files are store in binary format. • No need to encode and decode.
Binary I/O Program Input stream Input object created from an input class 01011… 1001 File output stream Output object created from an output class 11001… 1011 File 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” Encoding Decoding Binary I/O program A byte is read/written e. g. , ” 199” The encoding of the character is stored in the file 00110001 00111001 The encoding of the character is stored in the file 00110111 1 ※ 199 = 12 x 16 + 7 0 x. C 7 ※ Text I/O requires encoding and decoding, whereas binary I/O does not
Binary I/O Classes 課本 P. 676
程式範例: Test. File. Stream. java
Using Data. Input. Stream/Data. Output. Stream • Data streams constructors: public Data. Input. Stream(Input. Stream instream) public Data. Output. Stream(Output. Stream outstream) • Create data streams: Data. Input. Stream input = new Data. Input. Stream(new File. Input. Stream(“in. dat”)); Data. Output. Stream output = new Data. Output. Stream(new File. Output. Stream(“out. dat”));
程式範例: Test. Data. Stream. java
Buffered. Input. Stream/Buffered. Output. Stream • Buffered. Input. Stream/Buffered. Output. Stream can be used to speed up input and output by reducing number of reads and writes. • All the methods in Buffered. Input. Stream/Buffered. Output. Stream are inherited from the Input. Stream/Output. Stream classes
• 可在 Test. Data. Stream. java 的第 8行及第 22行加入: Data. Output. Stream output = new Data. Output. Stream(new Buffered. Output. Stream(new File. Output. Stream("temp. dat"))); Data. Input. Stream input = new Data. Input. Stream(new Buffered. Input. Stream(new File. Input. Stream("temp. dat")));
Copy File 程式範例: Copy. java ※ Java Copy source target
程式練習: Programming Exercises 19. 2
- Slides: 17