FileDescriptor
This class serves as a handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes. This handle can be err, in or out. It is used to create a FileInputStream or FileOutputStream to contain it. It inherits methods from the java.io.Object class.
Syntax:
public final class FileDescriptor extends Object
Methods of the class are as follows:
- void sync( ) Used to force all system buffers to synchronize with the underlying device
- boolean valid( ) Used to tests if the file descriptor is valid
The instance for a file descriptor class works as the opaque handle for the machine-specific structure that helps represent the open file, open socket, or bytes’ sink, or other sources.
Here are a few more things to know about the Java file descriptor:
- Fundamental and practical usage of a file descriptor is the creation of FileInputStream or FileOutputStream for containing it.
- Furthermore, the applications must not create their file descriptors.
- In case of void sync(), after writing all the modified data of FileDescriptor to an underlying device, this method is returned.
Fields of Java FileDescriptor:
Java file descriptor has three main fields as follows:
- err: It is the handle for the standard error stream.
- in: It is the handle to the standard input stream.
- out: It is the handle to the standard output stream.
Java FileDescriptor constructor:
FileDescriptor(0 is the constructor for the Java file descriptor, and it helps construct its object.
Example:
Com.knowledge2life
import java.io.*;
public class Main {
public static void main(String[] args) {
FileDescriptor fd = null;
byte[] b = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58 };
try {
FileOutputStream fos = new FileOutputStream("Record.txt");
FileInputStream fis = new FileInputStream("Record.txt");
fd = fos.getFD();
fos.write(b);
fos.flush();
fd.sync();
int value = 0;
while ((value = fis.read()) != -1) {
char c = (char) value;
System.out.print(c);
}
System.out.println("\nSync() successfully executed!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:
0123456789:
Sync() successfully executed!!