Java FileDescriptor Class
The java.io.FileDescriptor class represents an open file or socket handle in the underlying operating system. It acts as an opaque reference to a particular file, device, or socket. This class is mainly used as a bridge between Java I/O streams and the native file system resources.
Class Declaration
public final class FileDescriptor extends Object
- The main practical use for a file descriptor is to create a FileInputStream or FileOutputStream to contain it.
- Applications should not create their own file descriptors.
Common FileDescriptor Objects
- FileDescriptor.in: Represents the standard input (keyboard)
- FileDescriptor.out: Represents the standard output (console)
- FileDescriptor.err: Represents the standard error (error output)
Constructor
- FileDescriptor(): Creates an invalid file descriptor that is not connected to any file or socket.
Methods
There are two main methods as mentioned below:
- void sync(): Forces all system buffers to synchronize with the underlying device, ensuring that data is physically written.
- java.io.File.valid(): Checks whether the file descriptor object is valid (i.e., connected to an open file or socket).
Method Example
1. sync() Method
Syntax:
public void sync()
Return : void
Exception: SyncFailedException - This is exception is thrown if there is no guarantee of synchronization of buffers with the device.
import java.io.*;
public class FileDescriptorValidity {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("example.txt");
FileDescriptor fd = fos.getFD();
System.out.println("Is FileDescriptor valid? " + fd.valid());
fos.close();
System.out.println("Is FileDescriptor valid after close? " + fd.valid());
}
}
Output
Is FileDescriptor valid? true Is FileDescriptor valid after close? false
2. valid() Method
Syntax:
public boolean valid()
Return: true if the FileDescriptor object is valid else, false
import java.io.*;
public class FileDescriptorSync {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("syncDemo.txt");
FileDescriptor fd = fos.getFD();
fos.write("GeeksForGeeks FileDescriptor Example".getBytes());
fd.sync(); // Ensures data is written to disk
System.out.println("Data synchronized successfully.");
fos.close();
}
}
Output
Data synchronized successfully.
Example with Standard FileDescriptors
import java.io.*;
public class StandardFileDescriptors {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream(FileDescriptor.in);
FileOutputStream fos = new FileOutputStream(FileDescriptor.out);
FileOutputStream fes = new FileOutputStream(FileDescriptor.err);
fos.write("Enter something: ".getBytes());
int data = fis.read();
fes.write(("You entered: " + (char)data + "\n").getBytes());
fis.close();
fos.close();
fes.close();
}
}
Output:
Enter something: A
You entered: A