Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Java File Descriptor
3.
Fields, Constructors, and Methods
3.1.
Fields
3.2.
Constructors
3.3.
Methods
4.
Example
4.1.
Program
5.
The getFD() method
5.1.
Syntax
5.2.
Example
5.3.
Code
5.4.
Output
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

File Descriptor Class in Java

Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Any application needs to be able to handle files. Java provides numerous methods for generating, reading, updating, and deleting files.

We can use FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream, and other classes in the Java API to read and write files in Java. The Java version you're using determines which one to use, whether you need to read bytes or characters, and the file/line size, among other factors.

We will cover the File descriptor class of Java in this article.

Java File Descriptor

The operating system produces and maintains an entry to represent the file whenever the user opens a file. An integer value identifies each entry, referred to as a file descriptor.

The File descriptor instances act as an Implicit handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes. 

File descriptors should not be created by applications.

java.io.FileDescriptor is used to open files with specified names.

The most common usage of a file descriptor is to store it in a FileInputStream or FileOutputStream.

We get a File Descriptor object every time we create a FileInputStream or FileOutputStream object, and we may utilise this FileDescriptor object to build another FileInputStream or FileOutputStream object.

The declaration of the File Descriptor class:

public final class FileDescriptor extends Object
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Fields, Constructors, and Methods

Let's look at the Fields Constructor and Methods of Java FileDescriptor.

Fields

All the File Descriptor class fields have Static and final as access modifiers.

  • Err: err is a handle to the standard error stream.
  • In: in is a handle to the standard input stream.
  • Out: out is a handle to the standard output stream.

Constructors

The constructor of the java file descriptor is denoted as FileDescriptor().

The FileDescriptor() Constructort constructs the File Descriptor object. 

If a file does not exist, a FileNotFoundException will be thrown by the constructor that created the file descriptor object.

Accessing a file necessitates a security check, and if we do not have permission to access that file, a SecurityException is thrown by the constructor.

Methods

We mainly have two Java File Descriptor class methods, namely sync() and valid().

The sync() method is void type, and the valid() method is boolean.

The working of these methods are as follows:

  • sync(): This method is helpful for synchronisation purposes. It synchronises all the system buffers with the underlying system.  
  • Valid (): This method is advantageous in checking the validity of the file descriptor object.

Example

Here is an example of how to use File Descriptor in Java code.

Program

import java.io.FileDescriptor;
import java.io.FileOutputStream;


public class Main {
    public static void main(String[] args) throws Exception {
        FileOutputStream os = new FileOutputStream("Nofilename");
        FileDescriptor fd = os.getFD();
        os.write(1);
        os.flush();
        fd.sync();
    }
}

Also see, Duck Number in Java

The getFD() method

This method returns a FileDescriptor object representing the connection to the specific file in the file system that the current File Input Stream uses. It belongs to the java.io package and is a non-static method.

Syntax

The getFD() method's syntax declaration is as follows. It takes no parameters and returns the FileDescriptor object associated with the current stream.

public final FileDescriptor getFD()

Example

In this example, we'll utilise the FileInputStream class's getFD() function to retrieve a file descriptor in Java. Take a look at the sample below.

Code

package com.CodingNinjas;
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 finps = null;
      boolean bool = false;
      try {
         // new file input stream is created
         fis = new FileInputStream("C://example.txt");
         // get the file descriptor
         fd = finps.getFD();
         // tests the validity of the file
         bool = fd.valid();
         // prints
         System.out.println("The file is valid: "+bool)
      } catch(Exception ex) {
         // if an Input-output error occurs
         ex.printStackTrace();
      } finally {
         // releases all the system resources from the streams
         if(finps!=null)
            finps.close();
      }
   }
}

Content of the file example.txt:

Output

Try it by yourself on Java Online Compiler.

Must Read Type Conversion in Java

FAQs

  1. In Java, what is a stream?
    A Stream is a type of abstraction that can produce or consume data.
     
  2. What are the different types of I/O streams?
    Byte and Character streams are the two forms of I/O streams.
     
  3. What is serialisation, and how does it work?
    Serialisation is storing an object's state in a sequence of bytes. At the same time, deserialization is the process of recovering an object from these bytes. The Java Serialisation API provides a standard approach for constructing serializable objects.
If a folder does not exist, write code to create it.
File folder = new File(path);
if(!folder.exists()){
try {
folder.mkdir(); //mkdir stands for Make Directory
} catch (Exception e) {}
}

4. What do you understand by BufferedWriter? What are the purposes of flush() and close()?
BufferedWriter is a temporary data storage source. The character data is written to the file using BufferedWriter. Flush() is a BufferWriter method that assures that all data items, including the last character, are written to the file. The character output stream is closed using Close().

Key Takeaways

This article extensively discussed the Java File Descriptor class and its constructor, field, and methods. We have also seen the getFD() method and its Example. 

We hope this article has increased your understanding of the File Descriptor Class and File Handling in Java. If you want to learn more about File Input Output, you can visit this. Also, check out our article on File Input Stream class, Filter Input Output Stream Class, etc.

Please upvote our blog to assist other ninjas in their development.

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences, and much more!!

We wish you Good Luck! Keep coding and keep reading Ninja!!

 

Previous article
FileWriter
Next article
Random Access File class
Live masterclass