PUBLISHED ON: APRIL 3, 2021
Java FileInputStream getFD() Method
In this tutorial, we will learn about the getFD()
method of the FileInputStream class in Java. This method is used to return the object of the FileDescriptor that represents the connection to the specific file in the file system which is being used by the current File Input Stream. 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 it returns the FileDescriptor object which belongs to the current stream
public final FileDescriptor getFD()
Example: Get File Descriptor in Java
In this example, we are using getFD() method of FileInputStream class that is used to get file descriptor in Java. See the example below.
package com.studytonight;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.FileInputStream;
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
FileDescriptor fd = null;
FileInputStream fis = null;
boolean bool = false;
try {
// create new file input stream
fis = new FileInputStream("C://test.txt");
// get file descriptor
fd = fis.getFD();
// tests if the file is valid
bool = fd.valid();
// prints
System.out.println("Valid file: "+bool);
} catch(Exception ex) {
// if an I/O error occurs
ex.printStackTrace();
} finally {
// releases all system resources from the streams
if(fis!=null)
fis.close();
}
}
}
Text in file c:/test.txt
ABCDEF
Valid file: true
Example 2: Get File Descriptor in Java
In this example, we are using the by using getFD() method is to return FileDescriptor linked with the stream in Java. See the example below.
import java.io.*;
public class GetFDOfFIS {
public static void main(String[] args) throws Exception {
FileInputStream fis_stm = null;
FileDescriptor file_desc = null;
try {
fis_stm = new FileInputStream("C:\\studytonight.txt");
// By using getFD() method is to return
// FileDescriptor linked with the stream
file_desc = fis_stm.getFD();
System.out.println("fis_stm.getFD(): " + file_desc);
} 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 (fis_stm != null) {
fis_stm.close();
}
}
}
}
fis_stm.getFD(): java.io.FileDescriptor@7bfcd12c
Conclusion:
In this tutorial, we learned about the getFD()
method of the FileInputStream class in Java, which returns the FileDescriptor object which denotes the connection to the exact file in the file system which is being used by 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.