Advanced Java - VII - Java IO

Jalaz Kumar · September 16, 2020

Java I/O (Input and Output) is used to process the input and produce the output.

The java.io package contains all the classes required for input and output operations.

Sequence of data is called stream. Java uses stream to make I/O operations fast. 3 streams are created in Java automatically:

  • System.out
  • System.in
  • System.err

Output Stream

  • For writing data to a destination; file, array, peripheral device or socket.

  • Abstract class. Important methods:

    • public void write(byte[]) throws IOException
    • public void flush() throws IOException
    • public void close() throws IOException

OutputStream

Input Steam

  • For reading data from a source; file, array, peripheral device or socket.

  • Abstract class. Important methods:

    • public abstract int read() throws IOException
    • public int available() throws IOException
    • public void close() throws IOException

InputStream

Getting Inputs from Console

BufferedReader class

  • java.io.BufferedReader
import java.io.*;

public class BufferedReaderExample {    
    public static void main(String args[]) throws Exception {             
        InputStreamReader r = new InputStreamReader(System.in);    
        BufferedReader br = new BufferedReader(r);            
        System.out.println("Enter your name");    
        String name = br.readLine();    
        System.out.println("Welcome "+name);    
    }    
}

Scanner class

  • java.util.Scanner

  • Simplest way to get input in Java.

  • Breaks the input into tokens using a delimiter(default=” “)

  • Provides nextXXX() methods such as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc.

  import java.util.*;

  public class ScannerExample {    
       public static void main(String args[]) {                       
           String s = "Hello, This is Jalaz.";   
           Scanner scan = new Scanner(s);
           System.out.println("Boolean Result: " + scan.hasNext());   
           System.out.println("String: " +scan.nextLine());  
           scan.close();

           System.out.println("--------Enter Your Details-------- ");  
           Scanner in = new Scanner(System.in);  
           System.out.print("Enter your name: ");    
           String name = in.next();         
           System.out.print("Enter your age: ");  
           int i = in.nextInt();
           System.out.print("Enter your salary: ");  
           double d = in.nextDouble();  
           System.out.println("Name: " + name + "Age: " + i + "Salary: " + d);         
           in.close();           
           }    
  }

Handling text/data files

FileReader & FileWriter classes are prominently used for handling text files.

Unlike FileOutputStream class, no need to convert string into byte array as FileWriter provides method to write string directly.

TextFileWriter.java

import java.io.FileWriter;

public class TextFileWriter {  
    public static void main(String args[]){    
         try {    
           FileWriter fw = new FileWriter("/home/jalaz/tech/java.txt");    
           fw.write("These are articles written by Jalaz");    
           fw.close();    
          } catch(Exception e){ System.out.println(e); }     
     }    
}

TextFileReader.java

import java.io.FileReader;

public class TextFileReader {  
    public static void main(String args[]) throws Exception {    
          FileReader fr = new FileReader("/home/jalaz/tech/java.txt");    
          int i;    
          while((i=fr.read())!=-1)    
              System.out.print((char)i);    
          fr.close();  
    }    
}

Serialization & Deserialization

  • Mechanism of writing an object-state into byte-stream or vice-versa.

  • Mainly used in Hibernate, RMI, JPA etc.

  • Both are platform-independent: Its possible to serialize an object in a platform and deserialize in different platform.

  • For serializing the object, we call the writeObject() method of ObjectOutputStream class.

  • For deserialization, we call the readObject() method of ObjectInputStream class.

  • We must have to implement the Serializable interface for serializing the object.

  • Mainly used to travel object’s state on the network (which is known as marshaling).

    Serialization

  • java.io.Serializable is a marker interface just like Clonable and Remote. Marker interfaces has no data member and method.

  • The String class and all the wrapper classes implement the java.io.Serializable interface by default.

Employee.java

 import java.io.Serializable;

 public class Employee implements Serializable{  
    int id;  
    String name;  
    public Employee(int id, String name) {  
       this.id = id;  
       this.name = name;  
    }  
 }

Serializer.java

 import java.io.*;

 class Serializer {  
      public static void main(String args[]) {  
          try {  
             Employee e1 = new Employee(75655,"Jalaz Kumar");
             FileOutputStream fout = new FileOutputStream("indiamart.txt");  
             ObjectOutputStream out = new ObjectOutputStream(fout);  
             out.writeObject(e1);  
             out.flush();  
             out.close();  
          } catch(Exception e) { System.out.println(e); }  
      }  
  }

Deserializer.java

  import java.io.*;

  class Deserializer {  
      public static void main(String args[]) {  
          try {  
              ObjectInputStream in = new ObjectInputStream(new FileInputStream("indiamart.txt"));  
              Employee e = (Employee)in.readObject();   
              System.out.println(e.id+" "+e.name);
              in.close();  
          } catch(Exception e) { System.out.println(e); }  
      }  
  }

Handling CSV files

  • Reading using java.util.Scanner

    import java.io.*;  
    import java.util.Scanner;
    
    public class ReadCSVScanner {  
        public static void main(String[] args) throws Exception {  
            Scanner sc = new Scanner(new File("/home/jalaz/tech/check.csv"));  
            sc.useDelimiter(",");
            while (sc.hasNext())
                System.out.print(sc.next());
            sc.close();  
        }  
    }
    
  • com.opencsv (Recommended Way)
    • CSV parser library.

    • Supports all the basic CSV-type operations.

    • Java 7 is currently the minimum supported version.

    • Can also read TDF (Tab-Delimited File) file format.

    • Setting up:

      • In Maven, add the following to pom.xml:
        <dependency>
              <groupId>com.opencsv</groupId>
              <artifactId>opencsv</artifactId>
              <version>4.1</version>
          </dependency>
      
      • In Gradle, add the following in build.gradle:
        compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
      
      • In normal run, download the jar from Link. Either add this jar to project path or create a directory named lib, and add this jar to lib.
  • Reading using OpenCSV API

    import java.io.FileReader;
    import java.util.List;
    import com.opencsv.*;
    
    public class ReadCSVData {
        public static void main(String[] args) {
          try {
              FileReader filereader = new FileReader("/home/jalaz/tech/onebyone.csv");
              CSVReader csvReader = new CSVReader(filereader);
              String[] nextRecord;
    
              while ((nextRecord = csvReader.readNext()) != null) {
                  for (String cell:nextRecord) {
                      System.out.print(cell + "\t");
                  }
                  System.out.println();
              }
    
              //------------------------------------------------------------------------
    
              FileReader filereader = new FileReader("/home/jalaz/tech/allatonce.csv");
              CSVReader csvReader = new CSVReaderBuilder(filereader)
                                        .withSkipLines(1)
                                        .build();
              List<String[]> allData = csvReader.readAll();
    
              for (String[] row : allData) {
                  for (String cell : row) {
                      System.out.print(cell + "\t");
                  }
                  System.out.println();
              }
    
              //------------------------------------------------------------------------
    
              FileReader filereader = new FileReader("/home/jalaz/tech/colonseparated.csv");
              CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
              CSVReader csvReader = new CSVReaderBuilder(filereader)
                                        .withCSVParser(parser)
                                        .build();
    
              List<String[]> allData = csvReader.readAll();
    
              for (String[] row : allData) {
                  for (String cell : row) {
                      System.out.print(cell + "\t");
                  }
                  System.out.println();
              }
    
              //------------------------------------------------------------------------   
          }  
          catch (Exception e) {
              e.printStackTrace();
          }
        }
    }
    
  • Writing using OpenCSV API

    import java.io.*;
    import java.util.*;
    import com.opencsv.CSVWriter;
    
    public class WriteCSVData {
        public static void main(String[] args) {
            try {
                FileWriter outputfile = new FileWriter("/home/jalaz/tech/write.csv");
                CSVWriter writer = new CSVWriter(outputfile);
    
                List<String[]> data = new ArrayList<String[]>();
                data.add(new String[] { "Name", "RollNo", "Branch" });
                data.add(new String[] { "Jalaz", "14MI528", "CSE" });
                data.add(new String[] { "Sukhbir", "14MI535", "CSE" });
                writer.writeAll(data);
                writer.writeNext({"Saurabh", "14MI539", "CSE" });
                writer.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

Handling JSON files

  • json.simple
    • Lightweight JSON processing library

    • Used to read and write JSON files.

    • Used to encode or decode JSON text and is fully compliant with JSON specification.

    • JSON is widely used data-interchange formats and is lightweight and language independent.

    • In Maven, add the following to pom.xml:

      <dependency>
          <groupId>com.googlecode.json-simple</groupId>
          <artifactId>json-simple</artifactId>
          <version>1.1.1</version>
      </dependency>
      
  • Writing JSON to a file

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

import org.json.simple.JSONArray; import org.json.simple.JSONObject;

public class WriteJSONFile { public static void main( String[] args ) { JSONObject employeeDetails1 = new JSONObject(); employeeDetails1.put(“name”, “Jalaz Kumar”); employeeDetails1.put(“email”, “jalaz.kumar@indiamart.com”); JSONObject employeeObject1 = new JSONObject(); employeeObject1.put(“employee”, employeeDetails1);

     JSONObject employeeDetails2 = new JSONObject();
     employeeDetails2.put("name", "Narendra Dodwaria");
     employeeDetails2.put("email", "narendra.dodwaria@indiamart.com");
     JSONObject employeeObject2 = new JSONObject();
     employeeObject2.put("employee", employeeDetails2);

     JSONArray employeeList = new JSONArray();
     employeeList.add(employeeObject1);
     employeeList.add(employeeObject2);

     try (FileWriter file = new FileWriter("/home/jalaz/tech/employees.json")) {
         file.write(employeeList.toJSONString());
         file.flush();
     } catch (IOException e) {
         e.printStackTrace();
     }
 }  }    ```
  • Reading JSON from a file

    employees.json

    [
       {
           "employee": {
               "name": "Jalaz Kumar",
               "email": "jalaz.kumar@indiamart.com"
           }
       },
       {
           "employee": {
               "name": "Narendra Dodwaria",
               "email": "narendra.dodwaria@indiamart.com"
           }
       }
    ]
    

    ReadJSONFile.java ```java import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException;

import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException;

public class ReadJSONFile { public static void main(String[] args) { JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader(“employees.json”)){ Object obj = jsonParser.parse(reader); JSONArray employeeList = (JSONArray) obj;

         employeeList.forEach(emp -> parseEmployeeObject((JSONObject) emp));

     } catch (FileNotFoundException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     } catch (ParseException e) {
         e.printStackTrace();
     }
 }

 private static void parseEmployeeObject(JSONObject employee) {
     JSONObject employeeObject = (JSONObject) employee.get("employee");

     String name = (String) employeeObject.get("name");    
     System.out.println(name);
     String email = (String) employeeObject.get("email");    
     System.out.println(email);
 }  }    ```

Handling XML files

Reading XML file in Java is much different from reading other files like .docx and .txt because XML file contains data between the tags.

2 parsers in Java which parses an XML file:

  • DOM Parser
    • DOM API provides the classes to read and write an XML file.

    • Parses the entire XML file and creates a DOM object in the memory.

    • Everything in an XML file is a node. Node represents a component of an XML file.

    • Slow in process and occupies lots of memory during loading of an XML file into memory.

  • SAX Parser
    • Stands for Simple API for XML.

    • Parses an XML file line by line. It triggers events when it encounters the opening tag, closing tag, and character data in an xml file. Also called the event-based parser.

    • Does not load any XML file into memory.

    • It does not create any object representation of the XML document.

    • Faster and uses less memory than DOM parser.

  • Reading XML from a file using DOM API

sample.xml

 <?xml version="1.0"?>  
 <indiamart>  
     <employee>  
         <id>75655</id>  
         <name>Jalaz Kumar</name>
         <email>jalaz.kumar@indiamart.com</email>
     </employee>  

     <employee>  
         <id>75656</id>  
         <name>Atul Agarwal</name>
         <email>agarwal.atul1@indiamart.com</email>
     </employee>
 </indiamart>

ReadXMLFile.java

 import javax.xml.parsers.DocumentBuilderFactory;  
 import javax.xml.parsers.DocumentBuilder;

 import org.w3c.dom.Document;  
 import org.w3c.dom.NodeList;  
 import org.w3c.dom.Node;  
 import org.w3c.dom.Element;  
 import java.io.File;

 public class ReadXMLFile {  
     public static void main(String argv[]) {  
         try {  
             File file = new File("/home/jalaz/tech/sample.xml");
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
             DocumentBuilder db = dbf.newDocumentBuilder();  
             Document doc = db.parse(file);  
             doc.getDocumentElement().normalize();

             System.out.println("Root element: " + doc.getDocumentElement().getNodeName());  
             NodeList nodeList = doc.getElementsByTagName("employee");
             for(int itr = 0; itr < nodeList.getLength(); itr++) {  
                 Node node = nodeList.item(itr);  
                 System.out.println("\nNode Name :" + node.getNodeName());  
                 if (node.getNodeType() == Node.ELEMENT_NODE) {  
                     Element eElement = (Element) node;  
                     System.out.println("Student id: "+ eElement.getElementsByTagName("id").item(0).getTextContent());  
                     System.out.println("Name: "+ eElement.getElementsByTagName("name").item(0).getTextContent());
                     System.out.println("EMail: "+ eElement.getElementsByTagName("email").item(0).getTextContent());
                 }  
             }  
         } catch (Exception e) {  
              e.printStackTrace();  
         }  
     }  
 }

Twitter, Facebook