Java IO Handling

Java IO Handling

Java IO is an API that comes with Java which is targeted at reading and writing data (input and output). Most applications need to process some input and produce some output based on that input. For instance, read data from a file or over network, and write to a file or write a response back over the network.

File Management:

File file = new File("abc.txt");

if(!file.exists()){
     file.createNewFile();
}

Read a file:

FileInputStream fin = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));

 Read a line from a file:

String s;
while((s=br.readLine())!=null){
    system.out.println(s);
}

Read a character from a file:

int r;
while((r=fin.read())!=-1){
          char ch = (char) r;
          System.out.println(ch);
}

Writing to a file:

FileWriter fw = new FileWriter(file);
fw.write(“Hello world”); // write on stream
fw.flush(); // flush out to file

 Practical example of Java I/O:

Steps:
1. Create Item class
2. Create an InventoryManager Interface
3. Create an InventoryManagerImpl class which implements InventoryManager
4. Create a Test class

public class Item {

String name;
double price;

//Constructor
public Item(String name, double price) {
        this.name = name;
        this.price = price;
}

//Getters and Setters
public String getName() {
      return name;
}
public void setName(String name) {
      this.name = name;
}
public double getPrice() {
     return price;
}
public void setPrice(double price) {
      this.price = price;
}

@Override
public String toString() {
     return "Item [name=" + name + ", price=" + price + "]";
}

}

InventoryManager Interface

public interface InventoryManager {
      String file = "item.txt";
      public void addItem(Item item);

}

InventoryManagerImpl Class

import java.io.FileWriter;
import java.io.IOException;

public class InventoryManagerImpl implements InventoryManager {

     FileWriter f= null;

public InventoryManagerImpl(){
    try {
          f = new FileWriter(file);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

}

@Override
public void addItem(Item item) {
      String content = item.getName() + " "+ item.getPrice();
     try {
            f.write(content);
            f.flush();
     } catch (IOException e) {
        // TODO Auto-generated catch block
           e.printStackTrace();
     }

  }

}

Test Class

public class Test {

      public static void main(String[] args) {
      InventoryManager im = new InventoryManagerImpl();
      im.addItem(new Item("Desk", 35.50));

      }

}

Serialization / Deserialization :

Serialization : Represent an object into a binary format. It will save the whole object into binary format.
Deserialization : Convert from binary to object. Read back the binary format and convert it into object.

How to Serialize an Object?
An object can be serialized and deserialized if the class implements Serializable interface.

What if you don’t want to serialize some properties of the object?
Those properties need to marked as transient. For example, if you don’t want to serialize and age of Employee then just mark it like this
           transient int age;

Example: Write an object to file:
FileOutputStream fout = new FileOutputStream(anyFile);
ObjectOutputStream out = new ObjectOutputStream(fout);
Employee e = new Employee (“David”, 35);
out.writeObject(e); //Employee will be written to file in binary format
out.close();

Example: Read back from file :
FileInputStream fin = new FileInputStream(anyFile);
ObjectInputStream in = new ObjectInputStream(fout);
Employee e = in.readObject();
in.close();