Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP201 Java Programming Topic 6: Streams and Files Reading: Chapter 12.

Similar presentations


Presentation on theme: "COMP201 Java Programming Topic 6: Streams and Files Reading: Chapter 12."— Presentation transcript:

1 COMP201 Java Programming Topic 6: Streams and Files Reading: Chapter 12

2 COMP201 Topic 6 / Slide 2 Outline l Introduction and overview l Writing and reading text files l Writing and reading binary files l Writing and reading objects l File management

3 COMP201 Topic 6 / Slide 3 Introduction and Overview l When talking about IO, we need to consider files n Location: – blocks of main memory – local file system – over the net n Format: –text or binary – zipped or not zipped n Access mode: –plain sequential, –buffered, –pushback, –Random l Java has classes for all possible combinations.

4 COMP201 Topic 6 / Slide 4 Introduction and Overview l Java streams provide an abstraction of files at different locations: Local files and files from the net are handled in essentially the same way. In this lecture, we deal with only files on local machine. l Java has many (60+) stream classes for various file formats and access modes l We will cover only a few commonly used classes. l What follows is an overview of those 60+ classes. l Classes for reading text files l Classes for writing text files l Classes for reading binary files l Classes for writing binary files

5 COMP201 Topic 6 / Slide 5 Reader All classes for reading from text files descend from the abstract class Reader Reader has an method read, which returns the next unicode character or –1 (EOF) Reader LineNumber Reader Pushback Reader InputStream Reader CharArray Reader Filter Reader Buffered Reader String Reader Piped Reader File Reader

6 COMP201 Topic 6 / Slide 6 Writer All classes for writing to text files descend from the abstract class Writer Writer has an method write(int b), which writes a unicode character to an output Writer Print Writer File Writer Buffered Writer OutputStream Writer Piped Writer Filter Writer CharArray Writer String Writer

7 COMP201 Topic 6 / Slide 7 InputStream All classes for reading from binary files descend from the abstract class InputStream InputStream has one abstract method read, which returns the next byte character or –1 (EOF) InputStream Pushback InputStream LineNumber InputStream Data InputStream Buffered InputStream File InputStream ByteArray InputStream Filter InputStream Sequence InputStream StringBuffer InputStream Object InputStream Piped InputStream..

8 COMP201 Topic 6 / Slide 8 OutputStream All classes for writing to binary files descend from abstract class OutputStream OutputStream has one abstract method write(int b), which writes one byte to an output OutputStream Checked OutputStream PrintStream Data OutputStream Buffered OutputStream ByteArray OutputStream Filter OutputStream Object OutputStream Piped OutputStream.. File OutputStream

9 COMP201 Topic 6 / Slide 9 Writing Text Output l Writing to a text file: l Open a file for writing FileWriter f = new FileWriter(“employee.dat”); The FileWriter class has method, namely write, for writing contents of stream f to file “ employee.dat ”. l But it has no methods for putting information into the stream. Solution: nest FileWriter with PrintWriter PrintWriter out = new PrintWriter(f); Now you can use methods of PrintWriter out.print(…), out.println(…)// DataFileTest.java

10 COMP201 Topic 6 / Slide 10 Writing Text Output l Java uses Unicode characters: 2 bytes for each character. l User’s system might use a different encoding. E.g. Windows uses ISO 8859-1, i.e. ANSI code. Potential mismatch automatically dealt with by FileWriter 1. To be more precise, FileWriter is a combination of OutputStreamWriter and FileOutputStream. FileWriter f = new FileWriter(“employee.dat”); is equivalent to OutputStreamWriter f = new OutputStreamWriter( new FileOutputStream(“employee.dat”)); 2. OutputStreamWriter resolves the potential mismatch. 3. User can choose other encoding using new OutputStreamWriter(OutputStream, “Big5”)

11 COMP201 Topic 6 / Slide 11 Writing Text Output More Notes: Attempts to write to a file might result in IOException when, e.g., file system full or no write permission. As such, one needs deal with exceptions(either use the try/catch blocks or throw ). l PrintWriters are always buffered. close stream after use to flush out the the last bits. Can manually flush buffer using the flush method. Import java.io.*. System.out is a predefined OutputStreamWriter, stands for screen.

12 COMP201 Topic 6 / Slide 12 Writing Text Output public void writeData(PrintWriter out) throws IOException { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(hireDay); out.println(name + "|" + salary + "|" + calendar.get(Calendar.YEAR) + "|" + (calendar.get(Calendar.MONTH) + 1) + "|" + calendar.get(Calendar.DAY_OF_MONTH)); }

13 COMP201 Topic 6 / Slide 13 Reading Text Input l Reading a text file: l Open a file for reading FileReader f = new FileReader(“employee.dat”); Nest FileReader with BufferedReader so that you can extract information from stream f. BufferedReader in = new BufferedReader(f); l Now you can read lines in input as strings in.readLine(); Might throw IOException. DataFileTest.java

14 COMP201 Topic 6 / Slide 14 Reading Text Input l Reading a text file / Parsing input s = readLine() gives you a long string. l Need to break the string into individual strings and convert them into proper type. To do this, use the StringTokenizer class in java.util. Create a StringTokenizer object for the delimiter “|” StringTokenizer t = new StringTokenizer(s, “|”);

15 COMP201 Topic 6 / Slide 15 Reading Text Input Reading a text file / Parsing input Use the nextToken method to extract the next piece from string. t.nextToken () --- name. t.nextToken() --- salary as string. Needs Double.parseDouble t.nextToken() --- year as string. Needs Integer.parseInt t.nextToken() --- month as string. Needs Integer.parseInt t.nextToken() --- day as string. Needs Integer.parseInt l Here we know that there are 5 tokens on each line. In general, call t.hasMoreTokens before each t.nextToken DataFileTest.java

16 COMP201 Topic 6 / Slide 16 Reading Text Input public void readData(BufferedReader in) throws IOException { String s = in.readLine(); StringTokenizer t = new StringTokenizer(s, "|"); name = t.nextToken(); salary = Double.parseDouble(t.nextToken()); int y = Integer.parseInt(t.nextToken()); int m = Integer.parseInt(t.nextToken()); int d = Integer.parseInt(t.nextToken()); GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d); // GregorianCalendar uses 0 = January hireDay = calendar.getTime(); } //DataFileTest.java

17 COMP201 Topic 6 / Slide 17 Reading From the Keyboard System.in is a predefined InputStreamReader, stands for keyboard. import java.io.*; public class Echo { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String s; while((s = in.readLine()).length() != 0) System.out.println(s); // An empty line terminates the program } } //Echo.java

18 COMP201 Topic 6 / Slide 18 Writing Binary Files l Open a binary file for writing FileOutputStream out = new FileOutputStream(“employee.dat”); l Writing to a binary file byte b = 0; out.write( b ); // write a byte appears as 00 l Writing to a binary file out.write(int b); Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored. -- JDK 1.3 --

19 COMP201 Topic 6 / Slide 19 Writing Binary Files Suppose we want to write double, int, string, etc… to a binary file in buffered mode. l Open binary file for writing as follows: DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("employee.dat"))); l Now we can write simply using: out.writeChars( name + "\n" ); out.writeDouble(salary); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(hireDay); out.writeInt(calendar.get(Calendar.YEAR)); out.writeInt(calendar.get(Calendar.MONTH) + 1); out.writeInt(calendar.get(Calendar.DAY_OF_MONTH)); //BinaryFileTest.java

20 COMP201 Topic 6 / Slide 20 Reading Binary Files l Open a binary file for reading FileInputStream in = new FileInputStream(“employee.dat”); byte c = in.read(); // read a byte l Reading from a binary file int in.read(); Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. -- JDK 1.3 – Programs seldom read and write bytes. Combine with subclasses of FilterInputStream and FilterOutputStream (see slides 7 and 8) to construct desired streams.

21 COMP201 Topic 6 / Slide 21 Reading Binary Files To read double, int, string, etc … from a binary file in buffered mode, open binary file for reading as follows: DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream("employee.dat"))); l Now we can read by using: name = in.readLine() salary = in.readDouble(); int y = in.readInt(); int m = in.readInt(); int d = in.readInt(); GregorianCalendar calendar=new GregorianCalendar(y, m - 1,d); hireDay = calendar.getTime(); //BinaryFileTest.java //No need for StringTokenizer

22 COMP201 Topic 6 / Slide 22 Writing and Reading Objects l Tedious to do manually. l Java provides a mechanism called object serialization that makes this straightforward. l To save and read objects of a class, the class must implement the Serializable interface. class Employee implements Serializable { ….} Serializable has no methods. It is just a tag. l Not all classes are made serializable for security reasons.(P742)

23 COMP201 Topic 6 / Slide 23 Writing Objects To save an object, open an ObjectOutputStream ObjectOutputStream out = new ObjectOutputStream ( new FileOutputStream(“employee.dat”)); Simply use writeObject method to save an object Employee harry = new Employee("Harry Hacker", 35000, 1989,10,1); Manager carl = new Manager("Carl Cracker", 75000, 1987,12,15); out.writeObject(harry); out.writeObject(carl); If a superclass implements Serializable, a subclass does this automatically.

24 COMP201 Topic 6 / Slide 24 Reading Objects To get back an object, open an ObjectInputStream ObjectInputStream in = new ObjectInputStream ( new FileInputStream(“employee.dat”)); Use readObject method to retrieve objects in the same order in which they were written Employee[] newStaff = (Employee[]) in.readObject(); Cast necessary because readObject returns an object of class Object. l Strings and arrays can be handled this way since they are objects // ObjectFileTest.java

25 COMP201 Topic 6 / Slide 25 Writing and Reading Objects l The above scheme works even when objects have reference field. l Example: class Manager extend Employee { … private Employee secretary; } Employee harry = new Employee( …); Manager carl = new Manager(…); carl.setSecretary(harry); Manager tony = new Manager(…); tony.setSecretary(harry); secretary carltony harry

26 COMP201 Topic 6 / Slide 26 Writing and Reading Objects The following does not save three copies of harry out.writeObject(carl); out.writeObject(harry); out.writeObject(tony); l Here is what really happens: l Each object gets a unique serial number (1, 2,..) l When saving an object, find out whether the same object has already been stored. l If yes, just write “same as previously saved object with serial number x”. l Reading reverse the procedure. l All these are done automatically. //ObjectRefTest.java

27 COMP201 Topic 6 / Slide 27 A Diversion/Using serialization for cloning l Idea n Write an object to an output stream out.writeObject(someObeject) n Read it back in copy = in.readObject() Note: No need to write the object to a file. Write it to a byte array (an internal buffer) using ByteArrayOutputStream

28 COMP201 Topic 6 / Slide 28 ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out= new ObjectOutputStream(bout); out.writeObject(someObject); out.close(); // read a clone of the object from the byte array ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ObjectInputStream in = new ObjectInputStream(bin); Object copyOfObject = in.readObject(); in.close(); //SerialCloneTest.java A Diversion/Using serialization for cloning bout.toByteArray(): creates byte array and copy contents over

29 COMP201 Topic 6 / Slide 29 File Management Use java.io.File: A File object can represent either a file or a directory. Use the isDirectory and isFile methods to find out. l Creating a new directory: 1. Create a File object 1.File tempDir = new File( “temp”); 2. Make it a directory 1.tempDir.mkdir(); l Inspecting contents of a directory tempDir.list() returns an array of file names under the directory

30 COMP201 Topic 6 / Slide 30 File Management l Creating a new file 1. Create a File object: File foo = new File(“dirName”+File.separator + “data.txt”); File foo = new File(“dirName”, “data.txt”); 2. Create file 1.foo.createNewFile(): creates a file if no file with that name exists; l Deleting files and directories someDir.delete(); someFile.delete(); //FindDirectories.java


Download ppt "COMP201 Java Programming Topic 6: Streams and Files Reading: Chapter 12."

Similar presentations


Ads by Google