Presentation is loading. Please wait.

Presentation is loading. Please wait.

 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.

Similar presentations


Presentation on theme: " We can use a combination of the File and FileOutputStream to write a series of bytes to a file."— Presentation transcript:

1

2  We can use a combination of the File and FileOutputStream to write a series of bytes to a file

3  We can use a combination of the File and FileInputStream to read a series of bytes from the file

4

5  What if we want to perform file I/O on numerical values such as integers.  FileInput and FileOutput are limited in that they only deal with bytes  An integer takes 4 bytes (storage requirement)  By using DataOutputStream, we can output Java primitative data type values.

6

7 1. outDataStream: Primitive data types are written to outDataStream 2. outFileStream: Primitive data type values are converted to a sequence of bytes 3. outFile: Bytes are written to the file one at a time

8  To read the data back from the file, we reverse the operation.  We use 3 objects: File, FileInputStream and DataInputStream

9

10

11  Both FileOutputStream and DataOutputStream objects produce a binary file in which the contents are stored in the format (called binary format) in which they are stored in the main memory.  Instead of storing data in binary format, we can store them in ASCII format- all data is converted to a String format.  A file whose contents are stored in ASCII format is called a textfile. One major benefit of a textfile is that we can easily read and modify the contents using a word processor

12  PrintWriter is an object we use to generate a textfile.  PrintWriter supports only 2 output methods ◦ print ◦ println  An argument to the methods can be any primitive data type. The methods convert the parameter to string and output this string value before writing to a file

13

14  To read data from a textfile we use FileReader and BufferedReader objects.  The relationship between FileReader and BufferedReader is similar to the one between FileInputStream and DataInputStream.

15 import java.io.*; /** * A program to read data from a file using the readLine method of *BufferedReader for High-level I/O **/ public class TestBufferedReader { public static void main (String args[]) { try { //setup file and stream File inFile = new File("sample.data"); FileReader fileReader = new FileReader(inFile); BufferedReader bufReader = new BufferedReader(fileReader); //read values of primitive data types from the stream System.out.println(bufReader.readLine()); //input done so close the stream bufReader.close(); } catch (IOException e) { System.out.println("Error reading from file"); System.out.println("Error message "+e.toString()); }

16


Download ppt " We can use a combination of the File and FileOutputStream to write a series of bytes to a file."

Similar presentations


Ads by Google