Home » Java programming language

Java ObjectOutputStream drain() Method with Example

ObjectOutputStream Class drain() method: Here, we are going to learn about the drain() method of ObjectOutputStream Class with its syntax and example.
Submitted by Preeti Jain, on April 08, 2020

ObjectOutputStream Class drain() method

  • drain() method is available in java.io package.
  • drain() method is used to drain any of the buffered content in this ObjectOutputStream.
  • drain() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • drain() method may throw an exception at the time of draining buffered data.
    IOException: This exception may throw when getting any input/output error while writing from the output stream.

Syntax:

    protected void drain();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void drain() method of
// ObjectOutputStream

import java.io.*;

public class Drain extends ObjectOutputStream {
 public Drain(OutputStream os) throws IOException {
  super(os);
 }

 public static void main(String[] args) throws Exception {
  // Instantiates ObjectOutputStream , ObjectInputStream 
  // FileInputStream and FileOutputStream
  FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
  Drain obj_out_stm = new Drain(file_out_stm);
  FileInputStream file_in_stm = new FileInputStream("D:\\includehelp.txt");
  ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);

  // By using writeObject() method is to
  // write the object to the stream		
  obj_out_stm.writeInt(156924);

  // By using drain() method is to
  // drain the stream
  obj_out_stm.drain();

  // By using readObject() method is to 
  // read the object
  int in = (int) obj_in_stm.readInt();
  System.out.println("obj_in_stm.readInt(): " + in );

  // By using close() method is to 
  // close all the streams 
  System.out.println("Stream Shutdown... ");

  file_in_stm.close();
  file_out_stm.close();
  obj_in_stm.close();
  obj_out_stm.close();
 }
}

Output

obj_in_stm.readInt(): 156924
Stream Shutdown... 






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.