How to Serialize an array or Collection of objects

Hope you have already gone thru basic working of Serialization. To Serialize an array of objects of a class, below are the steps.
1. The class whose array of objects need to be serialized, has to implement java.io.Serializable interface
2. Create another class, which has an array or Collection of objects, as a data member. This class also has to implement Serializable interface.
3. Now, you can follow normal steps to Serialize class created in above, step2

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication2;

import java.io.Serializable;

class StudentInfo implements Serializable
{
 //transient data members will not take part in Serialization   
 String name;
int rid;
 StudentInfo(String n, int r)
 {
  this.name = n;
  this.rid = r;
 }

 void printStudentInfo()
 {
     System.out.println("StudentInfo details Test:"+name+" "+rid+" ");
 }
 
 public String toString()
 {
     return "name="+name+", id="+rid;
 }
}


class StudentInfoArray implements Serializable{
    StudentInfo arr[];
    
    StudentInfoArray(StudentInfo arr[])
    {
        this.arr = arr;
    }
}
package javaapplication2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeArray
{
    
 public static void main(String[] args)
 {
 try
 {
//Serialization starts here
  StudentInfo si1 = new StudentInfo("checkingnexttime", 310);
  
  StudentInfo si2 = new StudentInfo("checkingnexttime1", 311);
  
  StudentInfo si3 = new StudentInfo("checkingnexttime2", 312);
  
  StudentInfo sarr[] = {si1, si2, si3};
  
  StudentInfoArray sia = new StudentInfoArray(sarr);
  
  //.ser is a standard file extension, to store serialized object
  FileOutputStream fos = new FileOutputStream("C:\\student.ser");

  //instead of writing object stream to a file, it is also possible to send object thru 
  //Network using socket programming
  ObjectOutputStream oos = new ObjectOutputStream(fos);

  System.out.println("Serialing the object...");
  oos.writeObject(sia);
  oos.close();
  fos.close();  
  }
  catch (Exception e)
  { e. printStackTrace(); }
 }
}
package javaapplication2;

import java.io.*;

public class DeSerializeArray {
 public static void main(String[] args)
 {
 try
 {
  
  System.out.println("De serializing object...");
  //DeSerialization starts here
  FileInputStream fis = new FileInputStream("C:\\student.ser");
  ObjectInputStream ois = new ObjectInputStream(fis);
  StudentInfoArray toa = (StudentInfoArray)ois.readObject();

  System.out.println("before printing Object");

  for(StudentInfo si:toa.arr)//foreach
  {
      System.out.println(si);
  }
    
  //RMI(Remote Method Invocation) is based on Serialization/Deserialization
  }
  catch (Exception e)
  { e. printStackTrace(); }
    }
}

How to redirect System.out output to a file, instead of Console

You can read about standard input ans standard output stream details here. As known System.out represents Standard output stream, and anything written to standard output stream, gets displayed on console screen. How ever it is possible to redirect output of System.out to any OutputStream, like FileOutputStream, or to Network. Below is an example, on how to redirect the content written to System.out to a file name abcd.txt.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class SystemIORedirectDemo {
public static void main(String[] args) {
	try{
	FileOutputStream fos = new FileOutputStream("abcd.txt");
	PrintStream ps = new PrintStream(fos);
	System.setOut(ps);
	
	System.out.println("Hello, How are you");
	System.out.println("Note that this content is saved to abcd.txt file");
	}
	catch(IOException ioe)
	{
		System.out.println("IOException occurred:"+ioe.getMessage());
	}
}
}

By default, System.in reads each character from Keyboard. Below is an example on how to redirect System.in. Similarly it is also possible to redirect System.err

import java.io.FileInputStream;
import java.io.IOException;

public class SystemIORedirect1Demo {
public static void main(String[] args) throws IOException{
	FileInputStream fis = new FileInputStream("abcd.txt");
	
	System.setIn(fis);
	
	int i = 0;
	while(i != -1)
	{
	i = System.in.read();//reads each character from the file abcd.txt
	System.out.print((char)i);//prints the character read, above
	}
}
}

You may also like to read:

java standard input and output

How to Compress and Uncompress file in Java

A file or folder can be compressed in Java using any of the following classes

  1. DeflaterOutputStream
  2. GZIPOutputStream
  3. ZipOutputStream


Above classes are in the package java.util.zip. Also note that GZIPOutputStream and ZipOutputStream classes are derived from DeflaterOutputStream. Any one of them can be used to compress file or folder, they just differ in compress format.

Below is simple program to compress a file, using DeflaterOutputStream.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.DeflaterOutputStream;

public class CompressFile {
public static void main(String args[]){
	try {
FileOutputStream fos = new FileOutputStream("compressed.zip");
//assuming that abcd.txt file is in execution path of program
	FileInputStream fis = new FileInputStream("abcd.txt");

	DeflaterOutputStream dout = new DeflaterOutputStream(fos);
	int j;

	while((j=fis.read()) != -1)
        {
	dout.write((byte)j);

	dout.flush();
	}

	fis.close();
	fos.close();

}catch(Exception e){
System.out.println(e);
r.printStackTrace();
}
System.out.println("Done");
}
}


A compressed file or folder, can be uncompressed using any of below classes

  1. InflaterInputStream
  2. GZIPInputStream
  3. ZipInputStream

Above classes are in the package java.util.zip. Also note that GZIPInputStream and ZipInputStream classes are derived from InflaterInputStream.

Below is simple program to uncompress a file, using InflaterInputStream

import java.io.*;
import java.util.zip.InflaterInputStream;

class UnCompressFile{
public static void main(String args[]){

try{
FileOutputStream fos=new FileOutputStream("abcd.txt");

FileInputStream fis=new FileInputStream("compress.zip");
InflaterInputStream inf=new InflaterInputStream(fis);

int k;

while((k=inf.read())!=-1)
{
fos.write((byte)k);
fos.flush();
}

fis.close();
fos.close();
inf.close();

}catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
}
System.out.println("Done");
}
}

You may also like to read:
How to take input from Standard input
SequenceInputStream example
FileWriter and FileReader example

PipedInput OutputStream example

PipedInputStream and PipedOutputStream are classes provided in java.io package. PipedInputStream is inherited from InputStream, and PipedOutputStream is inherited from OutputStream.
A piped input stream should be connected to a piped output stream, using connect() method(as shown in below example). Data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. A pipe is said to be broken if a thread that was providing data bytes to the connected piped output stream is no longer alive.

Below is an example, in which main thread reads characters from PipedInputStream, and other thread writes characters to PipeOutputStream.


import java.io.*;

class MyThread extends Thread{
    static String str = "Hello How are you";
    //creating one thread t1 which writes the data
        public void run(){
            for(int i=0;i<=str.length();i++){
            try{
                PipedInputOutput1.pout.write(str.charAt(i));
                Thread.sleep(1000);  //1000 milliseconds
            }catch(Exception e){
            System.out.println(e.getMessage());
            }
            } //end of for
        }  //end of run()

}

class PipedInputOutput1{
    final static PipedOutputStream pout=new PipedOutputStream();
    final static PipedInputStream pin=new PipedInputStream();

    public static void main(String args[])throws Exception{
        pout.connect(pin);//connecting the streams

        MyThread t1 = new MyThread();
        //creating another thread t2 which reads the data

        //starting both threads
        t1.start();

        try{
            for(int i=0;i<=MyThread.str.length();i++)
            {
                System.out.println((char)pin.read());
            }
        }catch(Exception e){
        System.out.println(e.getMessage());
        }
    }
}


You may also like to read:
SequenceInputStream purpose
Convert String to a Stream
How to take input from key board
Java Serialization example

SequenceInputStream example

SequenceInputStream is used to combine multiple input streams, and creates single SequenceInputStream. And reading from this SequenceInputStream reads the input streams one after another.
Below is simple example showing how to use SequenceInputStream

import java.io.*;
class SequenceInputStreamDemo{
  public static void main(String args[]) throws Exception{

     FileInputStream fin1=new FileInputStream("f1.txt");
     FileInputStream fin2=new FileInputStream("f2.txt");
     FileInputStream fin4=new FileInputStream("f3.txt");

     FileOutputStream fout=new FileOutputStream("f4.txt");

     SequenceInputStream sis=new SequenceInputStream(fin1,fin2);

     SequenceInputStream sis1 = new SequenceInputStream(sis,fin4);

     int i;
     while((i=sis1.read())!=-1)
     {
        fout.write(i);
     }
     sis.close();
     fout.close();
     fin1.close();
     fin2.close();
  }
}

Purpose of transient keyword

transient keyword is used in serialization. A data member(of a class implementing Serializable interface) can be declared as transient, if it need not be serialized. Hence the data members declared as transient does not under go serialization.

For complete example, please read Java Serialization

Keyboard input

Below program is an example on how to input from a keyboard(standard input)

import java.io.*;
class KeyboardInput{
public static void main(String args[])throws Exception{

//System.out is standard output
//System.err is standard error output
//System.in is standard input stream
//InputStreamReader r=new InputStreamReader(new FileInputStream(“../abc.txt”));
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);

//System.in.read(); //reads only one character(at a time) from keyboard

String name=””;

//! is Logical NOT operator
while(!name.equals(“exit”)){
System.out.println(“Enter data: “);
name=br.readLine();
System.out.println(“data is: “+name);
}

br.close();
r.close();
}
}

Example of PrintWriter

package fileionavigationexample;
import java.io.*;
public class PrintWriterExample {
public static void main(String[] args){
File file = new File(“C:\Users\KUNDAN\Documents\AdvanceJavaNotes.txt”);
try{
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println(“Advance Java Is also Termed As Enterprise Edition ie. J2EE.”);
pw.println(“It includes Folowing Topics.”);
pw.println(“1) JDBC:Java Database Conectivity.”);
pw.println(“2) Servelet”);
pw.println(“3) JSP”);
pw.println(“4) Hibernate”);
pw.println(“5) Spring”);
pw.println(“6) Struts”);

pw.close();
fw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String f = br.readLine();
while((f = br.readLine()) != null){
System.out.println(f);
}
br.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}

Example Of BufferedWriter And BufferedReader

package fileionavigationexample;
/*All Belongs to java.io package
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
*/
import java.io.*;

public class BufferedWriterAndBufferedReader extends IOException {
public static void main(String[] args) throws IOException{
File file = new File(“C:\Users\KUNDAN\Documents\JavaNotes.txt”);

FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(“Features Of Java Programming Language:”);
bw.newLine();
bw.write(“1) Java is an Object Oriented Programming Language also called OOPS Language.”);
bw.newLine();
bw.write(“2) Java language is Highly Secured. Means It provides Third party security.”);
bw.newLine();
bw.write(“3) Java language is Robust. Means 24/7 it can be accesed by the user.”);
bw.newLine();
bw.write(“4) Java language is an scale oriented programming language. Means we can restrict an application for the number of users at a time.”);

bw.close();
fw.close();

FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String s = null;

while((s = br.readLine()) != null){
System.out.println(s);
}
fr.close();
br.close();

}
}

Example Of FileWriter And FileReader

package fileionavigationexample;
import java.io.*;
public class FileWriterAndFileReader {
public static void main(String[] args){
char[] in = new char[100];
int size = 0;
try{
File file = new File(“C:\Users\KUNDAN\Documents\Firsttext.txt”);
FileWriter fw = new FileWriter(file);//this is a file writer object “fw”.
fw.write(“Hello I am writing a story.”);//it is used to write character into the text file “Firsttext.txt”.
// fw.write(“Hello I am writing a story.”);
fw.close();

FileReader fr = new FileReader(file);
size = fr.read(in);//it reads the total number of bytes in a file.
for(char c:in){
System.out.print(c);
}
System.out.println(size); //return 26(21 letters + 5 spaces b/w letters)
fr.close();

}catch(IOException ex){
ex.printStackTrace();
}
}
}

/*
Output:
————-
Hello I am writing a story 26 bytes
*/