Home » Java programming language

Java FileOutputStream getChannel() Method with Example

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

FileOutputStream Class getChannel() method

  • getChannel() method is available in java.io package.
  • getChannel() method is used to return the distinct FileChannel linked with this FileOutputStream.
  • getChannel() 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.
  • getChannel() method does not throw an exception at the time of returning channel.

Syntax:

    public FileChannel getChannel();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is FileChannel, it returns the FileChannel linked with this FileOutputStream.

Example:

// Java program to demonstrate the example 
// of FileChannel getChannel() method 
// of FileOutputStream

import java.io.*;
import java.nio.channels.*;

public class GetChannelOfFOS {
 public static void main(String[] args) throws Exception {
  FileOutputStream fos_stm = null;
  FileChannel file_ch = null;
  int count = 0;

  try {
   // Instantiates FileOutputStream
   fos_stm = new FileOutputStream("D:\\includehelp.txt");

   // By using getChannel() method is to return
   // FileChannel linked with the stream	

   file_ch = fos_stm.getChannel();
   System.out.println("fos_stm.getChannel(): " + file_ch);
  } catch (Exception ex) {
   System.out.println(ex.toString());

  } finally {
   // with the help of this block is to
   // free all necessary resources linked
   // with the stream
   if (fos_stm != null) {
    fos_stm.close();

    if (file_ch != null) {
     file_ch.close();
    }
   }
  }
 }
}

Output

fos_stm.getChannel(): sun.nio.ch.FileChannelImpl@67117f44


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.