We can use a combination of the File and FileOutputStream to write a series of bytes to a file
We can use a combination of the File and FileInputStream to read a series of bytes from the file
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.
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
To read the data back from the file, we reverse the operation. We use 3 objects: File, FileInputStream and DataInputStream
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
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
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.
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()); }