File and Inputoutput Streams The File Class Data

  • Slides: 27
Download presentation
File and Input/output Streams

File and Input/output Streams

 • The File Class • Data stored in variables, arrays, and objects are

• The File Class • Data stored in variables, arrays, and objects are temporary; they are lost when the program terminates. • To permanently store the data created in a program, you need to save them in a file on a disk or a CD. • File class is present in java. io package and It deals directly with files and the file system. • Every file is placed in a directory in the file system. • An absolute file name contains a file name with its complete path and drive letter. • For example, c: bookWelcome. java is the absolute file name for the file Welcome. java on the Windows operating system. Here c: book is referred to as the directory path for the file. • Absolute file names are machine dependent

 • Do not use absolute file names in your program. Why? • You

• Do not use absolute file names in your program. Why? • You should use a file name relative to the current directory. Known as relative path For example, • you may create a File object using new File("Welcome. java") for the file Welcome. java in the current directory. • You may create a File object using new File(“abc/Welcome. java"). • The forward slash(/) is the Java directory separator, which will work same as in other platform. • The File class does not specify how information is retrieved from or stored in files. • File class can be used to obtain or manipulate the information associated with a disk file, such as file permissions, renaming or delete a file.

 • A directory is a File that contains a list of other files

• A directory is a File that contains a list of other files and directories. • The following constructors can be used to create File objects:

Methods in File class:

Methods in File class:

 • public boolean create. New. File() throws IOException: Atomically creates a new, empty

• public boolean create. New. File() throws IOException: Atomically creates a new, empty file named if and only if a file with this name does not yet exist. • 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.

 • • • class File. Demo { public static void main(String args[]) {

• • • class File. Demo { public static void main(String args[]) { File f 1 = new File("a. txt"); • System. out. println("File Name: " + f 1. get. Name()); • System. out. println("Path: " + f 1. get. Path()); • System. out. println("Is Absolute : " + f 1. is. Absolute()); • System. out. println("Absolute Path: " + f 1. get. Absolute. Path()); • System. out. println("Parent: " + f 1. get. Parent()); • System. out. println(f 1. exists() ? "exists" : "does not exist"); • System. out. println("Is a Directory: "+ f 1. is. Directory()); • System. out. println("Is a File: "+ f 1. is. File()); • System. out. println("Can Write? "+ f 1. can. Write()); • System. out. println("Can Read? "+ f 1. can. Read()); • System. out. println("File last modified: " + f 1. last. Modified()); • • • System. out. println("File size: " + f 1. length() + " Bytes"); } }

 • Text I/O vs Binary I/O • Data stored in a binary file

• Text I/O vs Binary I/O • Data stored in a binary file are represented in binary form. You cannot read binary files. They are designed to be read by programs. • Computers do not differentiate binary files and text files. All files are stored in binary format, and thus all files are essentially binary files. • Text I/O is built upon binary I/O to provide a level of abstraction for character encoding and decoding. • Encoding and decoding are automatically performed by the for text I/O.

The Concept of a Stream • A stream is a flow of data. The

The Concept of a Stream • A stream is a flow of data. The data might be characters, numbers, or bytes consisting of binary digits. • If the data flows into your program, the stream is called an input stream. • If the data flows out of your program, the stream is called an output stream. • For example, if an input stream is connected to the keyboard, the data flows from the keyboard into your program. If an input stream is connected to a file, the data flows from the file into your program. Figure below illustrates some of these streams.

Byte Streams and Character Streams • Java defines two types of streams: byte and

Byte Streams and Character Streams • Java defines two types of streams: byte and character. • Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. • Character streams provide a convenient means for handling input and output of characters. • At the lowest level, all I/O is byte-oriented. The character-based streams simply provide a convenient and efficient means for handling characters.

File. Input. Stream • The File. Input. Stream class creates an Input. Stream that

File. Input. Stream • The File. Input. Stream class creates an Input. Stream that you can use to read bytes from a file. Its two most common constructors are shown here: File. Input. Stream(String filepath) File. Input. Stream(File file. Obj) • Either can throw a File. Not. Found. Exception. Here, filepathis the full path name of a file, and file. Obj is a File object that describes the file.

File. Output. Stream • File. Output. Stream creates an Output. Stream that you can

File. Output. Stream • File. Output. Stream creates an Output. Stream that you can use to write bytes to a file. Its most commonly used constructors are shown here: File. Output. Stream(String file. Path) File. Output. Stream(File file. Obj) File. Output. Stream(String file. Path, boolean append) File. Output. Stream(File file. Obj, boolean append) • They can throw a File. Not. Found. Exception. Here, file. Pathis the full path name of a file, and file. Objis a. Fileobject that describes the file. Ifappend is true, the file is opened in append mode. • Creation of a File. Output. Stream is not dependent on the file already existing. File. Output. Stream will create the file before opening it for output when you create the object. In the case where you attempt to open a read -only file, an. IOExceptionwill be thrown.

 • Closing a stream when it's no longer needed is very important —

• Closing a stream when it's no longer needed is very important — • (1) closing a stream ensures that data will be written to the file. • (2) closing a stream release resource acquired by the stream object.

Program: 1 • import java. io. *; • class A • { • public

Program: 1 • import java. io. *; • class A • { • public static void main(String [] ar) • { • try • { • File. Output. Stream fos = new File. Output. Stream("a. dat"); • • • for(int i=1; i<=100; i++) { fos. write(i); • • • File. Input. Stream fis = new File. Input. Stream("a. dat"); int i; while((i = fis. read())!=-1) { System. out. println(i); } fis. close(); }catch(Exception e){System. out. println(e); } } fos. close(); } }

Program 2: • import java. io. *; • class B • { • public

Program 2: • import java. io. *; • class B • { • public static void main(String [] ar) • { • try • { • File. Output. Stream fos = new File. Output. Stream("b. dat"); • String s = "my first program of file handling"; • byte [] b = new byte[s. length()]; • • • b= s. get. Bytes(); System. out. println("Array b is"); for(int i=0; i<10; i++) { System. out. print(b[i]+" "); } System. out. println(); fos. write(b); fos. close(); File. Input. Stream fis = new File. Input. Stream("b. dat"); int i; System. out. println("Remaining bytes are"+fis. available()); while((i = fis. read())!=-1) { System. out. println("Remaining bytes are"+fis. available()); System. out. print((char)i); } fis. close(); }catch(Exception e){} } }

 • Writing Data into file using Print. Writer • The java. io. Print.

• Writing Data into file using Print. Writer • The java. io. Print. Writer class can be used to create a file and write data to a text file. • Print. Writer output = new. Print. Writer(filename); • Then, you can invoke the print, println methods on Print. Writer object

 • public class Print. Writer. Demo • { • public static void main(String[]

• public class Print. Writer. Demo • { • public static void main(String[] args) throws Exception { • java. io. File f = new java. io. File("b. txt"); • java. io. Print. Writer output = new java. io. Print. Writer(f); • • output. print("Java class "); • output. println(40); • output. print("LPU "); • output. println(85. 5); • output. print('a'); • • • output. close(); } }

 • Reading file Using Scanner • The java. util. Scanner class was used

• Reading file Using Scanner • The java. util. Scanner class was used to read strings and primitive values from the console • Scanner input = new Scanner(System. in); • To read from a file, create a Scanner for a file, as follows: • Scanner input = new Scanner(new File(filename));

 • import java. util. Scanner; • • • public class Read. File {

• import java. util. Scanner; • • • public class Read. File { public static void main(String[] args) throws Exception { • • java. io. File file = new java. io. File("b. txt"); Scanner input = new Scanner(file); • • • while(input. has. Next()) { String s = input. next. Line(); System. out. println(s); } • • • input. close(); } }

 • Object I/O • Object. Input. Stream/Object. Output. Stream enables you to perform

• Object I/O • Object. Input. Stream/Object. Output. Stream enables you to perform I/O for objects in addition to primitive type values and strings. • Since Object. Input. Stream/ Object. Output. Stream contains all the functions of Data. Input. Stream/ Data. Output. Stream,

Serialization • Serialization is the process of writing the state of an object to

Serialization • Serialization is the process of writing the state of an object to a byte stream. • This is useful when we want to save the state of our program to a persistent storage area, such as a file. • At a later time, we may restore these objects by using the process of de-serialization.

Serialization: Interfaces and Classes • An overview of the interfaces and classes that support

Serialization: Interfaces and Classes • An overview of the interfaces and classes that support serialization follows: Serializable – Only an object that implements the Serializable interface can be saved and restored by the serialization facilities. – The Serializable interface defines no members. – It is simply used to indicate that a class may be serialized. – If a class is serializable, all of its subclasses are also serializable.

Object. Output • The Object. Output interface extends the Data. Output interface and supports

Object. Output • The Object. Output interface extends the Data. Output interface and supports object serialization. • It defines the methods several methods. All of these methods will throw an IOExceptionon error conditions. • write. Object( )method is called to serialize an object. Output. Stream • The Object. Output. Stream class extends the Output. Stream class and implements the Object. Output interface. • It is responsible for writing objects to a stream. Constructor is: Object. Output. Stream(Output. Stream out. Stream) throws IOException • The argument out. Stream is the output stream to which serialized objects will be written.

Object. Output • The Object. Input interface extends the Data. Input interface. • It

Object. Output • The Object. Input interface extends the Data. Input interface. • It defines the methods several methods. All of these methods will throw an IOExceptionon error conditions. • read. Object( )method is called to deserialize an object. The read. Object( ) method can also throw Class. Not. Found. Exception. Object. Input. Stream • The Object. Input. Stream class extends the Input. Stream class and implements the Object. Input interface. • Object. Input. Stream is responsible for reading objects from a stream. • A constructor of this class is : Object. Input. Stream(Input. Stream in. Stream) throws IOException

Serialization Example class My. Class implements Serializable { String s; int i; double d;

Serialization Example class My. Class implements Serializable { String s; int i; double d; public My. Class(String s, int i, double d) { this. s = s; this. i = i; this. d = d; } public String to. String() { return "s=" + s + "; i=" + i + "; d=" + d; } }

import java. io. *; public class Serialization. Demo { public static void main(String args[])

import java. io. *; public class Serialization. Demo { public static void main(String args[]) { try { My. Class object 1 = new My. Class("Hello", -7, 2. 70); System. out. println("object 1: " + object 1); File. Output. Stream fos = new File. Output. Stream("serial"); Object. Output. Stream oos = new Object. Output. Stream(fos); oos. write. Object(object 1); oos. flush(); oos. close(); } catch(IOException e) { System. out. println("Exception during serialization: " + e); System. exit(0); }

// Object deserialization try { My. Class object 2; File. Input. Stream fis =

// Object deserialization try { My. Class object 2; File. Input. Stream fis = new File. Input. Stream("serial"); Object. Input. Stream ois = new Object. Input. Stream(fis); object 2 = (My. Class)ois. read. Object(); ois. close(); System. out. println("object 2: " + object 2); } catch(Exception e) { System. out. println("Exception during deserialization: " + e); System. exit(0); } } }