PUBLISHED ON: APRIL 3, 2021
Java FileInputStream getChannel() Method
In this tutorial, we will learn about the getChannel()
method of the FileInputStream class in Java. This method is used to return the discrete FileChannel object connected with this FIle Input Stream. The position of the returned channel is the number of bytes read from the file till now. It is a non-static method, available in the java.io package.
Syntax
This is the syntax declaration of this method. It does not accept any parameter and returns the FileChannel linked with this Input Stream.
public FileChannel getChannel()
Example 1: FileChannel object in Java
In this example, we are using getChannel() method of the FileChannel class that returns an object of FileChannel.
package com.studytonight;
import java.io.IOException;
import java.io.FileInputStream;
import java.nio.channels.FileChannel;
public class Studytonight {
public static void main(String[] args) throws IOException {
FileChannel fc = null;
FileInputStream fis = null;
int i = 0;
long pos;
char c;
try {
fis = new FileInputStream("E:/Studytonight/output.txt");
while((i = fis.read())!=-1) {
fc = fis.getChannel();
pos = fc.position();
c = (char)i;
System.out.print("No of bytes read: "+pos);
System.out.println("; Char read: "+c);
}
} catch(Exception ex) {
System.out.println("IOException: close called before read()");
} finally {
if(fis!=null)
fis.close();
if(fc!=null)
fc.close();
}
}
}
Output.txt
CURIOUS
No of bytes read: 1; Char read: C
No of bytes read: 2; Char read: U
No of bytes read: 3; Char read: R
No of bytes read: 4; Char read: I
No of bytes read: 5; Char read: O
No of bytes read: 6; Char read: U
No of bytes read: 6; Char read: S
Example 2: FileChannel object in Java
This is another example to get filechannel object of a file in Java that we can use to read and write data into the file.
import java.io.*;
import java.nio.channels.*;
public class Studytonight {
public static void main(String[] args) throws Exception {
FileInputStream st = null;
FileChannel std = null;
int count = 0;
try {
st = new FileInputStream("E:\Studytonight\output.txt");
while ((count = st.read()) != -1) {
count = st.read();
byte b = (byte) count;
System.out.println("st.read(): " + b);
}
std = fis_stm.getChannel();
System.out.println("st.getChannel(): " + std);
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
if (st != null) {
st.close();
if (std != null) {
std.close();
}
}
}
}
}
st.read(): 4
st.read(): 97
st.read(): 97
st.read(): 8
st.read(): 111
st.read(): 108
st.read(): 33
st.read(): 33
st.getChannel(): sun.nio.ch.FileChannelImpl@31b7dea0
Conclusion:
In this tutorial, we learned about the getChannel()
method of the FileInputStream class in Java, which returns the specific FileChannel associated with the current File Input Stream. 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.