Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.

Similar presentations


Presentation on theme: "Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with."— Presentation transcript:

1 Java File I/O (Continued)

2 File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with different formats. It is achieved via the following set of classes java.io.PrintWriter; java.io.FileOutputStream; java.util.Scanner; java.io.FileInputStream; java.io.BufferedReader; java.io.FileReader; …… File I/O is important!

3 Streams Byte stream: perform input and output of 8-bit bytes. In the later File IO FileInputStream and FileOutputStream are byte streams that allow the program to read and write binary files.FileInputStreamFileOutputStream Character stream: perform input and output of 16-bit bytes (i.e. Unicode) for text file reading and writing.

4 Input Character Stream Input stream class hierarchy for character stream, where Reader is the root and an abstract class. Its derived classes are used to fetch data from different sources, such as char array, String objects, files, pipe, and others.

5 Output Character Stream Output stream class hierarchy for character stream, where Writer is the root and an abstract class. Its derived classes are used to write data to different devices. These sub-classes have correspondence to the input stream sub classes.

6 Summary of Text File IO How to write? Use PrintWriter class to create an object This object has the similar methods as System.out such as print(…) and println(…) PrintWriter outputStreamName = new PrintWriter( new FileOutputStream(FileName)); PrintWriter outputStreamName = new PrintWriter(FileName);

7 Summary of Text File IO How to read? Use Scanner class to create an object This object uses methods, like nextInt(), nextDouble(), nextLong(), nextLine()… to read the corresponding data units one-by-one. Scanner StreamObject = new Scanner(new FileInputStream(FileName)); This object uses methods, like hasnextInt(), hasnextDouble(), hasnextLong(), hasnextLine()… to determine the end of the file.

8 Summary of Text File IO How to read? Use BufferedReader class to create an object BufferedReader readerObject; readerObject = new BufferedReader(new FileReader(FileName)); The object uses functions, readLine() and read() to read from the file. How to determine the end of the file? if readLine() return null or read() return -1.

9 Exercise Write a complete Java program using a Scanner object that opens a text file name “auto.txt” and display each line on screen (you must use exception handling).

10 Exercise Write a complete Java program using a Scanner object that opens a text file name “auto.txt” and display each line on screen (you must use exception handling). import java.util.*; import java.io.*; public class Midterm2_File { public static void main(String[] args) { try{ Scanner input = new Scanner (new FileInputStream("autos.txt")); while (input.hasNextLine()) { System.out.println(input.nextLine()); } input.close(); } catch(FileNotFoundException e) { System.out.println(e); System.exit(0); }

11 Exercise How to merge two existing text files into one?

12 Exercise How to merge two existing text files into one? import java.util.*; import java.io.*; public class MergeTwoTextFiles { public static void main(String[] args) { Scanner input; PrintWriter output; try{ input = new Scanner (new FileInputStream("file1.txt")); output = new PrintWriter(new FileOutputStream("file2.txt",true)); output.println(""); while (input.hasNextLine()) { output.println(input.nextLine()); } input.close(); output.close(); } catch(FileNotFoundException e) { System.out.println(e); System.exit(0); }

13 The File Class The File class is like a wrapper class for file names – The constructor for the class File takes a name, (known as the abstract name) as a string argument, and produces an object that represents the file with that name – The File object and methods of the class File can be used to determine information about the file and its properties import java.io.File; public class FileDemo { public static void main(String[ ] args) throws Exception { File f = new File(“test.txt"); f.createNewFile(); } }

14 Some Methods in the Class File (Part 1 of 5)

15 Some Methods in the Class File (Part 2 of 5)

16 Some Methods in the Class File (Part 3 of 5)

17 Some Methods in the Class File (Part 4 of 5)

18 Some Methods in the Class File (Part 5 of 5)

19 Java Binary Files Examples? How can you tell whether a file is a binary or not? Binary files store data in the same format used by computer memory to store the values of variables, i.e., binary digits No conversion needs to be performed when a value is stored or retrieved from a binary file

20 Binary File I/O Java binary files, unlike other binary language files, are portable A binary file created by a Java program can be moved from one computer to another These files can then be read by a Java program, but only by a Java program

21 Output Stream Output stream class hierarchy for byte stream, where OutputStream is the root and an abstract class. Its derived classes are used to write data to different devices. These sub-classes have correspondence to the input stream sub classes.

22 Input Stream Input stream class hierarchy for byte stream, where InputStream is the root and an abstract class. Its derived classes are used to fetch data from different sources, such as byte array, String objects, files, pipe, and others.

23 Writing Simple Data to a Binary File The class ObjectOutputStream is a stream class that can be used to write to a binary file – An object of this class has methods to write strings, values of primitive types, and objects to a binary file A program using ObjectOutputStream needs to import several classes from package java.io : import java.io.ObjectOutputStream; import java.io.FileOutStream; import java.io.IOException;

24 Opening a Binary File for Output An ObjectOutputStream object is created and connected to a binary file as follows: ObjectOutputStream outputStreamName = new ObjectOutputStream(new FileOutputStream(FileName)); The constructor for FileOutputStream may throw a FileNotFoundException The constructor for ObjectOutputStream may throw an IOException Each of these must be handled

25 Opening a Binary File for Output ObjectOutputStream outputStreamName = new ObjectOutputStream(new FileOutputStream(FileName)); Methods used to output primitive values include writeInt, writeDouble, writeChar, and writeBoolean The method writeUTF can be used to output values of type String. The stream should be closed after writing.

26 Some Methods in the Class ObjectOutputStream (Part 1 of 5) 10-26 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

27 Some Methods in the Class ObjectOutputStream (Part 2 of 5) 10-27 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

28 Some Methods in the Class ObjectOutputStream (Part 3 of 5) 10-28 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

29 Some Methods in the Class ObjectOutputStream (Part 4 of 5) 10-29 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

30 Some Methods in the Class ObjectOutputStream (Part 5 of 5) 10-30 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

31 Example Simply convert a text file into a binary format import java.util.*; import java.io.*; public class TextToBinary { public static void main(String[] args) { Scanner input; ObjectOutputStream output; try { input = new Scanner(new FileInputStream("file1.txt")); output = new ObjectOutputStream(new FileOutputStream("file1_bin.bin")); while(input.hasNextLine()) { output.writeUTF(input.nextLine()); } input.close(); output.close(); } catch(FileNotFoundException e) { System.out.println("Cannot find the file" + e); System.exit(0); } catch(IOException e) { System.out.println("Read/write exception" + e); System.exit(0); }

32 Reading Simple Data from a Binary File The class ObjectInputStream is a stream class that can be used to read from a binary file – An object of this class has methods to read strings, values of primitive types, and objects from a binary file A program using ObjectInputStream needs to import several classes from package java.io : import java.io.ObjectInputStream; import java.io.FileInputStream; import java.io.IOException;

33 Opening a Binary File for Reading An ObjectInputStream object is created and connected to a binary file as follows: ObjectInputStream inStreamName = new ObjectInputStream(new FileInputStream(FileName)); The constructor for FileInputStream may throw a FileNotFoundException The constructor for ObjectInputStream may throw an IOException Each of these must be handled

34 Opening a Binary File for Reading Methods used to input primitive values include readInt, readDouble, readChar, and readBoolean The method readUTF is used to input values of type String. If the file contains multiple types, each item type must be read in exactly the same order it was written to the file. The stream should be closed after reading. ObjectInputStream inStreamName = new ObjectInputStream(new FileInputStream(FileName));

35 Checking for the End of a Binary File the Correct Way All of the ObjectInputStream methods that read from a binary file throw an EOFException when trying to read beyond the end of a file – This can be used to end a loop that reads all the data in a file Note that different file-reading methods check for the end of a file in different ways – Testing for the end of a file in the wrong way can cause a program to go into an infinite loop or terminate abnormally

36 Some Methods in the Class ObjectInputStream (Part 1 of 5) 10-36 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

37 Some Methods in the Class ObjectInputStream (Part 2 of 5) 10-37 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

38 Some Methods in the Class ObjectInputStream (Part 3 of 5) 10-38 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

39 Some Methods in the Class ObjectInputStream (Part 4 of 5) 10-39 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

40 Some Methods in the Class ObjectInputStream (Part 5 of 5) 10-40 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

41 Example Read back the binary file we just converted. import java.io.*; public class ReadATextToBinaryFile { public static void main(String[] args) { ObjectInputStream inStream; try { inStream = new ObjectInputStream (new FileInputStream("file1_bin.bin")); char ch; while ((ch = (char)inStream.readByte())!=-1) System.out.print(ch); inStream.close(); } catch(FileNotFoundException e) { System.out.println("Cannot find the file" + e); System.exit(0); } catch(IOException e) { System.out.println("Read/write exception" + e); System.exit(0); }

42 Binary I/O of Objects Objects can also be input and output from a binary file – Use the writeObject method of the class ObjectOutputStream to write an object to a binary file – Use the readObject method of the class ObjectInputStream to read an object from a binary file – In order to use the value returned by readObject as an object of a class, it must be type cast first: SomeClass someObject = (SomeClass)objectInputStream.readObject();

43 Binary I/O of Objects It is best to store the data of only one class type in any one file – Storing objects of multiple class types or objects of one class type mixed with primitives can lead to loss of data In addition, the class of the object being read or written must implement the Serializable interface – The Serializable interface is easy to use and requires no knowledge of interfaces – A class that implements the Serializable interface is said to be a serializable class

44 The Serializable Interface In order to make a class serializable, simply add implements Serializable to the heading of the class definition public class SomeClass implements Serializable When a serializable class has instance variables of a class type, then all those classes must be serializable also – A class is not serializable unless the classes for all instance variables are also serializable for all levels of instance variables within classes

45 Example import java.io.ObjectOutputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.FileNotFoundException; /** Demonstrates binary file I/O of serializable class objects. */ public class ObjectIODemo { public static void main(String[] args) { try { ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("datafile")); SomeClass oneObject = new SomeClass(1, 'A'); SomeClass anotherObject = new SomeClass(42, 'Z'); outputStream.writeObject(oneObject); outputStream.writeObject(anotherObject); outputStream.close( ); System.out.println("Data sent to file."); } catch(IOException e) { System.out.println("Problem with file output."); } System.out.println( "Now let's reopen the file and display the data."); try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("datafile")); SomeClass readOne = (SomeClass)inputStream.readObject( ); SomeClass readTwo = (SomeClass)inputStream.readObject( ); System.out.println("The following were read from the file:"); System.out.println(readOne); System.out.println(readTwo); } catch(FileNotFoundException e) { System.out.println("Cannot find datafile."); } catch(ClassNotFoundException e) { System.out.println("Problems with file input."); } catch(IOException e) { System.out.println("Problems with file input."); } System.out.println("End of program."); } import java.io.Serializable; public class SomeClass implements Serializable { private int number; private char letter; public SomeClass( ) { number = 0; letter = 'A'; } public SomeClass(int theNumber, char theLetter) { number = theNumber; letter = theLetter; } public String toString( ) { return "Number = " + number + " Letter = " + letter; }

46 Recall: standard IO Under Java.language.System, we have the following static final InputStream in static final PrintStream out static final PrintStream err Standard input stream, input from keyboard or other user-specified input source Standard output stream, write to screen or other user-specified output devices Standard error message stream, write to screen or other user-specified output devices

47 Exercise Read a sequence of integer numbers from a text file, find out the minimum and maximum number, compute the median value.

48 Java Pipe java.nio.channels.Pipe public abstract class Pipe extends ObjectObject A pair of channels that implements a unidirectional pipe. A pipe consists of a pair of channels: A writable sink channel and a readable source channel. Once some bytes are written to the sink channel they can be read from source channel in exactly the order in which they were written.sink source Whether or not a thread writing bytes to a pipe will block until another thread reads those bytes, or some previously-written bytes, from the pipe is system- dependent and therefore unspecified. Many pipe implementations will buffer up to a certain number of bytes between the sink and source channels, but such buffering should not be assumed.

49 FilterReader: abstract class for reading filtered character streams CharArrayReader: This class implements a character buffer that can be used as a character-input stream.


Download ppt "Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with."

Similar presentations


Ads by Google