Chapter 16 Simple Input and Output Prerequisites for part Iv Chapter 8 Inheritance and Polymorphism Chapter 15 Exceptions and assertions Chapter 16 Simple Input and Output 与人玫瑰,手有余香 Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output Prerequisites for Part IV Chapter 8 Inheritance and Polymorphism Chapter 16 Simple Input and Output Chapter 15 Exceptions and Assertions 与人玫瑰,手有余香
Objectives discover file properties, delete and rename files using the File class 16.2 To understand how I/O is processed in Java(S 16.3) To distinguish between text I/O and binary I/O(8 16.3) To read and write characters using FileReader and FileWriter(8 16.4) To improve the performance of text IO using Buffered Reader and Buffered Writer(816.4) To write primitive values, strings, and objects as text using Print Writer and Printstream(§164) To read and write bytes using FileInputStream and File OutputStream(8 16.6) To read and write primitive values and strings using DataInput Stream/Data QutputStream(8 16.6) To store and restore objects using ObjectOutputStream and ObjectInputStream, and to understand how objects are serialized and what kind of objects can be serialized(s 16.9 Optional) To use the Serializable interface to enable objects to be serializable($ 16.9 Optional) To use RandomAccessFile for both read andweriteal. yu1610 Optional)
Liang,Introduction to Java Programming,revised by Dai-kaiyu 2 Objectives To discover file properties, delete and rename files using the File class (§16.2). To understand how I/O is processed in Java (§16.3). To distinguish between text I/O and binary I/O (§16.3). To read and write characters using FileReader and FileWriter (§16.4). To improve the performance of text I/O using BufferedReader and BufferedWriter (§16.4). To write primitive values, strings, and objects as text using PrintWriter and PrintStream(§16.4). To read and write bytes using FileInputStreamand FileOutputStream (§16.6). To read and write primitive values and strings using DataInputStream/DataOutputStream(§16.6). To store and restore objects using ObjectOutputStreamand ObjectInputStream, and to understand how objects are serialized and what kind of objects can be serialized (§16.9 Optional). To use the Serializable interface to enable objects to be serializable (§16.9 Optional). To use RandomAccessFile for both read and write. (§16.10 Optional)
Introduction ● files OLong-term storage of large amounts of data PErsistent data exists after termination of program O Files stored on secondary storage devices Magnetic disks ● Optical disks Magnetic tapes O Sequential and random access files Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 3 Introduction ⚫Files Long-term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices ⚫Magnetic disks ⚫Optical disks ⚫Magnetic tapes Sequential and random access files
The File class The File class is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion The filename is a string .The File class is a wrapper class for the file name and its directory path Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 4 The File Class ⚫The File class is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. The filename is a string. ⚫The File class is a wrapper class for the file name and its directory path
java.io. File Obtaining file +File(pathname: String) Creates a File object for the specified pathname. The pathname may be a ctory or a file properties an +File(parent: String, child: String) Creates a File object for the child under the directory parent. child may be a manipulating file filename or a subdirectory. +File(parent: File, child: String)Creates a File object for the child under the directory parent. parent is a File object. In the preceding constructor, the parent is a string +exists: boolean Returns true if the file or the directory represented by the file object exists +canReado: boolean Returns true if the file represented by the file object exists and can be read +can Write(: boolean Returns true if the file represented by the File object exists and can be written +isDirectoryO: boolean Returns true if the File object represents a directory +isFile(: boolean Returns true if the File object represents a file isAbsoluteO): boolean Returns true if the File object is created using an ab atn name +isHiddeno: boolean Returns true if the file represented in the File object is hidden. The exact definition of hidden is system-dependent. On Windows, you can mark a file hidden in the File Properties dialog box. On Unix systems, a file is hidden if its name begins with a period character getAbsolutePathO: String Returns the complete absolute file or directory name represented by the File +getCanonicalPathO: String Returns the same as get AbsolutePatho except that it removes redundant names, such as"."and".", from the pathname, resolves symbolic links(on Unix platforms), and converts drive letters to standard uppercase(on Win32 +getName( String Returns the last name of the complete directory and file name represented by the File object. For example, new File("c: booklltest dat").getNameO returns +getPatho: String Returns the complete directory and file name represented by the File object For example, new File("c: \lbookltest dat").get Patho returns c: \bookltest dat etParento: string Returns the complete parent directory of the current directory or the file represented by the File object. For example, new File("c: lbooklltest dat")-getParento returns c: \book +lastModifiedo long Returns the time that the file was last modified delete(: boolean Deletes this file. The method returns true if the deletion succeeds +renameTo(dest: File): boolean Renames this file. The method returns true if the operation succeeds
Liang,Introduction to Java Programming,revised by Dai-kaiyu 5 java.io.File +File(pathname: String) +File(parent: String, child: String) +File(parent: File, child: String) +exists(): boolean +canRead(): boolean +canWrite(): boolean +isDirectory(): boolean +isFile(): boolean +isAbsolute(): boolean +isHidden(): boolean +getAbsolutePath(): String +getCanonicalPath(): String +getName(): String +getPath(): String +getParent(): String +lastModified(): long +delete(): boolean +renameTo(dest: File): boolean Creates a File object for the specified pathname. The pathname may be a directory or a file. Creates a File object for the child under the directory parent. child may be a filename or a subdirectory. Creates a File object for the child under the directory parent. parent is a File object. In the preceding constructor, the parent is a string. Returns true if the file or the directory represented by the File object exists. Returns true if the file represented by the File object exists and can be read. Returns true if the file represented by the File object exists and can be written. Returns true if the File object represents a directory. Returns true if the File object represents a file. Returns true if the File object is created using an absolute path name. Returns true if the file represented in the File object is hidden. The exact definition of hidden is system-dependent. On Windows, you can mark a file hidden in the File Properties dialog box. On Unix systems, a file is hidden if its name begins with a period character '.'. Returns the complete absolute file or directory name represented by the File object. Returns the same as getAbsolutePath() except that it removes redundant names, such as "." and "..", from the pathname, resolves symbolic links (on Unix platforms), and converts drive letters to standard uppercase (on Win32 platforms). Returns the last name of the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getName() returns test.dat. Returns the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat. Returns the complete parent directory of the current directory or the file represented by the File object. For example, new File("c:\\book\\test.dat").getParent() returns c:\book. Returns the time that the file was last modified. Deletes this file. The method returns true if the deletion succeeds. Renames this file. The method returns true if the operation succeeds. Obtaining file properties and manipulating file
Example 16.1 Using the File class Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the file class to obtain their properties. Figure 16. 1 shows a sample run of the program on Windows, and Figure 16.2 a sample run on Unix Command Prompt COMmand Prompt-telnet panda :\book >java TestFileclass oes it exist? true home /liang/bool an it be read? true java TestFilecla an it be written? true Does it s it a directory false an it be read? true Is it a file? tr an it be written? true Is it absolute? false it a directory? false Is it hidden? false s it a file? tr hat s it absolute? false s ath? C: \book\\image\ hat is its canonical path? C: \book\image\us. gif what is its absolute path?/home/liang/book/, /image/us. gif nical is its nam hen was it last modified? Sat May 08 14: 00: 34 EDT 1999 at is its path? ./ lmage /us, a1 What is the path separator? Then was it last modi fied? Wed Jan 23 11: 00: 14 EST 2002 hat is the name separator? What is the path separator? hat is the name separator? C: \book> Liang, Introduction to Java Programming TestFileclass Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu 6 Example 16.1 Using the File Class TestFileClass Run Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the File class to obtain their properties. Figure 16.1 shows a sample run of the program on Windows, and Figure 16.2 a sample run on Unix
How is io handled in java? A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform 1/O, you need to create objects using appropriate Java 1/O classes FileReader input new FileReader("temp. txt)i int code input read()i system. out. println((char)code. O Return the unicode of the created from an input class reated from an File output class Output stream FileWriter output new FileWriter("temp. txt")i output. write("Java 101)i output. close()i Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 7 How is I/O Handled in Java? A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. Program Input object created from an input class Output object created from an output class Input stream Output stream File File FileWriter output = new FileWriter("temp.txt"); output.write("Java 101"); output.close(); FileReader input = new FileReader("temp.txt"); int code = input.read(); System.out.println((char)code); Return the unicode of the char
Coding essentials Declaring exception in the method Using try-catch block public static void main(String [ args) public static void main(String[] args) throws工 EXception Filewriter output FileWriter output new FileWriter(temp. txt)i new FileWriter("temp. txt)i output. write("Java 101) output. write("Java 101 )i tput close()i output. close()i FileReader input FileReader input new FileReader(temp. txt) new FileReader(temp. txt)i nt cod input. read() int code input read()i System. out. printin((char) code)i System. out. println((char)code)i put close() catch (IOException ex) t ex printstackTrace()i Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 8 Coding Essentials public static void main(String[] args) throws IOException { FileWriter output = new FileWriter("temp.txt"); output.write("Java 101"); output.close(); FileReader input = new FileReader("temp.txt"); int code = input.read(); System.out.println((char)code); input.close(); } Declaring exception in the method public static void main(String[] args) { try { FileWriter output = new FileWriter("temp.txt"); output.write("Java 101"); output.close(); FileReader input = new FileReader("temp.txt"); int code = input.read(); System.out.println((char)code); input.close(); } catch (IOException ex) { ex.printStackTrace(); } } Using try-catch block
Text File vs. Binary File o Data stored in a text file are represented in human-readable form Data stored in a binary file are represented in binary form You cannot read binary files. binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor but the Java classes are stored in binary files and are read by the jVm. The advantage of binary files is that they are more efficient to process than text files. o you can imagine that a text file consists ofa sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: 19,9 in a text file and the same integer is stored as a byte-type value cl in a binary file, because decimal 199 equals to hex C7 Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 9 Text File vs. Binary File ⚫ Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. ⚫ you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals to hex C7
Text l/o classes Inputstream Reader FileReader Reader Buffered Reader Object Buffered write Writer OutputStream Writer File writer Print writer Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 10 Text I/O Classes Reader Writer Object PrintWriter BufferedWriter FileReader FileWriter InputStreamReader BufferedReader OutputStreamWriter