Download presentation
Presentation is loading. Please wait.
1
Java @Ch19. Binary I/O 2011.05.06
2
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
3
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();
4
Read: // Using Scanner class Scanner input = new Scanner(new File(“temp.txt”)); System.out.println(input.nextLine()); // input.nextLine() 回傳 “Java 101”
5
Chap 9. WriteData
6
Chap 9. ReadData
7
Binary I/O All files are store in binary format. No need to encode and decode.
8
Binary I/O Program Input object created from an input class Output object created from an output class File 01011…1001 11001…1011 Input stream output stream The program receives data and send data
9
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 00110001 00111001 00111001 Encoding Decoding Binary I/O program A byte is read/written e.g.,”199” The encoding of the character is stored in the file 00110111 ※ Text I/O requires encoding and decoding, whereas binary I/O does not ※ 199 = 12 x16 + 7 0xC7 1
10
Binary I/O Classes 課本 P.676
11
程式範例 : TestFileStream.java
12
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”));
13
程式範例 : TestDataStream.java
14
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
15
可在 TestDataStream.java 的第 8 行及第 22 行加入 : DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("temp.dat"))); DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream("temp.dat")));
16
Copy File 程式範例 : Copy.java ※ Java Copy source target
17
程式練習 : Programming Exercises 19.2
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.