There are different ways in Java to read data from files and to write data to files.
1. Using Scanner
Scanner can be used to read input from the user. It can read all the primitive data types.
Scanner obj = new Scanner(System.in);
String input = obj.nextLine();
2. Using FileReader
FileReader can be used to read character data from a file. It returns the ASCII value for each character and -1 at the end.
FileReader fr=new FileReader("D:\\test.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
3. Using FileInputStream
FileInputStream can be used to read raw data (non-character) from a file. It returns a byte stream.
File file = new File("D:\\test.jpg");
FileInputStream in = new FileInputStream(file); // convert image to byte stream
byte[] arr = new byte[(int)(file.length())];
in.read(arr); // convert byte stream to byte array
in.close();
Serialization
Combining the features of FileInputStream and ObjectInputStream gives a new possibility. FileInputStream converts raw file data to byte stream and ObjectInputStream converts byte stream to object. Similarly, FileOutputStream converts byte stream to raw file and ObjectOutputStream converts object to byte stream. This process of converting an object into a stream of bytes is called Serialization. The main purpose is to transmit the object over a network and recreate the object later. Though JSON is the most preferred way of Serialization, Java provides its own default way.
The class needs to implement the Serializable marker interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient. When the class will be de-serialized, the transient variable will be initialized with a default value. The serialVersionUID attribute needs to be added in the class to verify that sender and receiver of the serialized object is the same.
FileOutputStream out = new FileOutputStream(filePath);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
objectOutputStream.writeObject(obj); // serialization
FileInputStream in = new FileInputStream(filePath);
ObjectInputStream objectInputStream = new ObjectInputStream(in);
obj = (Obj) objectInputStream.readObject(); //de-serialization
Externalizable is an Interface that extends Serializable Interface and sends data into Streams in Compressed Format.