Object-Oriented Programming - Lecture 5: I/O Streams - Lê Hồng Phương

✦ Byte streams ✦ Character streams ✦ Buffered streams ✦ Scanning and formatting ✦ I/O from the command line ✦ Data streams ✦ Object streams I/O streams ✦ An I/O stream represents an input source and an output destination. ✦ Different kinds of source and destination: ✦ disk files, devices, other programs, memory arrays. ✦ Different kinds of data: ✦ simple bytes, primitive data types, objects.

pdf30 trang | Chia sẻ: candy98 | Lượt xem: 466 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Object-Oriented Programming - Lecture 5: I/O Streams - Lê Hồng Phương, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
August 2012 Object-Oriented Programming Lecture 5: I/O Streams Dr. Lê H!ng Ph"#ng -- Department of Mathematics, Mechanics and Informatics, VNUH 1 Thursday, August 2, 12 Content ✦ Byte streams ✦ Character streams ✦ Buffered streams ✦ Scanning and formatting ✦ I/O from the command line ✦ Data streams ✦ Object streams 2 Thursday, August 2, 12 I/O streams ✦ An I/O stream represents an input source and an output destination. ✦ Different kinds of source and destination: ✦ disk files, devices, other programs, memory arrays. ✦ Different kinds of data: ✦ simple bytes, primitive data types, objects. 3 Thursday, August 2, 12 I/O streams ✦ A stream is a sequence of data. ✦ A program uses an input stream to read data from a source, one item at a time. ✦ A program uses an output stream to write data to a destination, one item at a time. 4 Thursday, August 2, 12 Byte streams ✦ Programs use byte streams to perform input and output on 8-bit bytes. ✦ There are many byte stream classes. ✦ All of them are descended from InputStream and OutputStream. ✦ File I/O byte streams: FileInputStream and FileOutputStream. 5 Thursday, August 2, 12 Byte streams public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } 6 Thursday, August 2, 12 Byte streams ✦ A simple loop that reads the input stream and writes the output stream, one byte at a time. ✦ Notice that read() returns an int value, which allow it to use -1 to indicate that it reaches the end of the stream. ✦ Always close streams: very important! ✦ The finally block guarantees that the streams will be closed even if an error occurs. ✦ This helps avoid serious leaks. 7 Thursday, August 2, 12 When not to use byte streams? ✦ CopyBytes represents a kind of low-level I/O that you should avoid. ✦ Because the input.txt contains character data, the best approach is to use character streams. ✦ Why should talk about byte streams? ✦ Because all other stream types are built on byte streams. 8 Thursday, August 2, 12 Content ✦ Byte streams ✦ Character streams ✦ Buffered streams ✦ Scanning and formatting ✦ I/O from the command line ✦ Data streams ✦ Object streams 9 Thursday, August 2, 12 Character streams ✦ The Java platform stores character values using Unicode conventions. ✦ A program that uses character streams automatically adapts to the local character set (Vietnamese locale, US locales...) ✦ All character stream classes are descended from Reader and Writer. ✦ File I/O character streams: FileReader and FileWriter. 10 Thursday, August 2, 12 Character streams public class CopyCharacters { public static void main(String[] args) throws IOException { FileReader inputStream = null; FileWriter outputStream = null; try { inputStream = new FileReader("input.txt"); outputStream = new FileWriter("output.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } } 11 Thursday, August 2, 12 Line-oriented I/O public class CopyLines { public static void main(String[] args) throws IOException { BufferedReader inputStream = null; PrintWriter outputStream = null; try { inputStream = new BufferedReader(new FileReader("input.txt")); outputStream = new PrintWriter(new FileWriter("output.txt")); String l; while ((l = inputStream.readLine()) != null) { outputStream.println(l); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } } 12 Thursday, August 2, 12 Content ✦ Byte streams ✦ Character streams ✦ Buffered streams ✦ Scanning and formatting ✦ I/O from the command line ✦ Data streams ✦ Object streams 13 Thursday, August 2, 12 Buffered streams ✦ Unbuffered I/O: each read or write request is handled directly by the underlying operating system. ✦ This makes a program much less efficient since each such request often triggers disk access, network activity or other expensive operations. ✦ Buffered I/O is much more efficient: ✦ Read/write data from/to a memory area known as a buffer ✦ The native input/output API is called only when the buffer is empty or full. 14 Thursday, August 2, 12 Buffered streams ✦ Convert an unbuffered stream into a buffered one using wrapping: ✦ There are 4 buffered stream classes used to wrap unbuffered streams: ✦ BufferedInputStream, BufferedOutputStream: buffered byte streams ✦ BufferedReader, BufferedWriter: buffered character streams. ✦ Flushing the buffer manually: invoke method flush(). BufferedReader bufferedReader = new BufferedReader(new FileReader("input.txt")); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("output.txt")); 15 Thursday, August 2, 12 Content ✦ Byte streams ✦ Character streams ✦ Buffered streams ✦ Scanning and formatting ✦ I/O from the command line ✦ Data streams ✦ Object streams 16 Thursday, August 2, 12 Scanning ✦ Objects of type Scanner are useful for ✦ breaking down formatted input into tokens; ✦ translating individual tokens according to their data types. 17 Thursday, August 2, 12 Breaking input into tokens ✦ A scanner uses white spaces (blanks, tabs, line terminators) to separate tokens. ✦ Use regular expressions to specify a different separator: public class ScanInput { public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("input.txt"))); while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) { s.close(); } } } } s.useDelimiter(",\\s*"); 18 Thursday, August 2, 12 Translating individual tokens ✦ Scanner also supports tokens for all of the primitive types. ✦ Numeric values can use thousands separators: ✦ 32,767 is an integer value in a US locale. ✦ Example: ScanSum reads a list of doubles and adds them up. 19 Thursday, August 2, 12 Translating individual tokens public class ScanSum { public static void main(String[] args) throws IOException { Scanner s = null; double sum = 0; try { s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt"))); s.useLocale(Locale.US); while (s.hasNext()) { if (s.hasNextDouble()) { sum += s.nextDouble(); } else { s.next(); } } } finally { s.close(); } System.out.println(sum); } } 8.5 32,767 3.14159 1,000,000.1 The output string is "1032778.74159" 20 Thursday, August 2, 12 Formatting ✦ Stream objects that implement formatting are instance of either ✦ PrintWriter, a character stream class or ✦ PrintStream, a byte stream class. ✦ These class implement ✦ standard write() methods for simple byte and character output; ✦ a set of methods for converting internal data into formatted output. 21 Thursday, August 2, 12 Formatting public class Root { public static void main(String[] args) { int i = 2; double r = Math.sqrt(i); System.out.format("The square root of %d is %f.%n", i, r); } } The square root of 2 is 1.414214. • d formats an integer value as a decimal value. • f formats a floating point value as a decimal value. • n outputs a platform-specific line terminator. • x formats an integer as a hexadecimal value. • s formats any value as a string. • tB formats an integer as a locale-specific month name. System.out.format("%f, %1$+020.10f %n", Math.PI); 3.141593, +00000003.1415926536 22 Thursday, August 2, 12 Content ✦ Byte streams ✦ Character streams ✦ Buffered streams ✦ Scanning and formatting ✦ I/O from the command line ✦ Data streams ✦ Object streams 23 Thursday, August 2, 12 I/O from the command line ✦ A program is often run from the command line and interacts with the user in the command line environment. Two ways: ✦ through standard streams; ✦ through the Console. ✦ Standard streams: System.in, System.out, System.err. ✦ System.in is a byte stream with no character stream features. To use the standard input as a character stream, do as follows: ✦ Console: a single, predefined object that has most features provided by the standard streams. It is particularly useful for secure password entry. InputStreamReader cin = new InputStreamReader(System.in); 24 Thursday, August 2, 12 Content ✦ Byte streams ✦ Character streams ✦ Buffered streams ✦ Scanning and formatting ✦ I/O from the command line ✦ Data streams ✦ Object streams 25 Thursday, August 2, 12 Data streams ✦ Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float and double) and String values. ✦ All data streams implement either DataInput or DataOutput interface. ✦ Two widely-used implementations: DataInputStream, DataOutputStream. DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile))); out.writeDouble(price); out.writeInt(unit); out.writeUTF(desc); DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile))); double price = in.readDouble(); int unit = in.readInt(); String desc = in.readUTF(); 26 Thursday, August 2, 12 Content ✦ Byte streams ✦ Character streams ✦ Buffered streams ✦ Scanning and formatting ✦ I/O from the command line ✦ Data streams ✦ Object streams 27 Thursday, August 2, 12 Object streams ✦ Object streams support I/O of objects. Classes support serialization of their objects if they implement the interface Serializable. ✦ The object stream classes: ObjectInputStream, ObjectOutputStream. ✦ These classes implements ObjectInput and ObjectOutput, which are subinterfaces of DataInput and DataOutput. ✦ This means that all the primitive data I/O methods supported by data streams are also implemented in object streams. ObjectOutputStream out = null; out = new ObjectOutputStream(new BufferedOutputStream( new FileOutputStream(dataFile))); out.writeObject(Calendar.getInstance()); ObjectInputStream in = null; in = new ObjectInputStream(new BufferedInputStream( new FileInputStream(dataFile))) Calendar date = (Calendar) in.readObject(); 28 Thursday, August 2, 12 Exercises ✦ Exercises 1. Write a program which creates a Deck object representing a deck of cards (cf. previous exercises). Then: ✦ Shuffles (randomly) the deck; ✦ Saves the deck into a text file, each cards in a line; ✦ Loads the file and restores the deck. 29 Thursday, August 2, 12 Exercises ✦ Exercise 2. Write a class Student which represents a student whose fields are id (int), name (String), mark (double). ✦ Creates n students (n > 4) whose data are read from the standard input; ✦ Saves the students to a binary file using data streams; ✦ Loads the saved file to restore and print the students to the standard output. ✦ Exercises 3. Same as Exercises 2 but using object streams to save and load data instead of data streams. 30 Thursday, August 2, 12
Tài liệu liên quan