當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java FileInputStream getFD()用法及代碼示例

Java.io.FileInputStream.getFD() 方法是 Java.io.FileInputStream 類的一部分。此方法將返回與文件輸入流關聯的 FileDescriptor 對象。

  • getFD() 方法被聲明為 final,這意味著 getFD() 不能在子類中被覆蓋
  • 我們將使用 getFD() 方法獲得的 FileDescriptor 對象將表示與文件係統中實際文件的連接
  • getFD() 方法可能會拋出 IOException。

用法:

public final FileDescriptor getFD() throws IOException

返回類型:getFD() 方法將返回與此 FileInputStream 關​​聯的 FileDescriptor 實例。

異常:如果引發任何輸入/輸出異常,getFD() 方法可能會拋出 IOException。



如何調用 getFD() 方法?

第 1 步:首先,我們必須創建一個 Java.io.FileInputStream 類的實例

FileInputStream  fileInputStream =new FileInputStream("tmp.txt");

步驟 2:要獲取與此 fileInputStream 關​​聯的 FileDescriptor 實例,我們將調用 getFD() 方法

FileDescriptor fileDescriptor =fileInputStream.getFD();

示例:Java 程序獲取 FileDescriptor 的實例,然後檢查它是否有效

在下麵的程序中,我們將

  • 使用 Java.io.FileInputStream.getFD() 方法獲取 FileDescriptor 的對象
  • 使用 FileDescriptor valid() 方法檢查文件描述符的實例是否有效

Java


// Java Program to get an instance
// of FileDescriptor and then to
// check it is valid or not
  
import java.io.*;
class GFG {
    public static void main(String[] args)
    {
        try {
            // create instance of FileInputStream class
            // user should change name of the file
            FileInputStream fileInputStream
                = new FileInputStream(
                    "C://geeksforgeeks//tmp.txt");
  
            // if the specified file does not exist
            if (fileInputStream == null) {
                System.out.println(
                    "Cannot find the specified file");
                return;
            }
  
            // to get the object of FileDescriptor for
            // this specified fileInputStream
            FileDescriptor fileDescriptor
                = fileInputStream.getFD();
  
            // check if the fileDescriptor is valid or not
            // using it's valid method
            // valid() will return true if valid else false
            System.out.println("Is FileDescriptor valid:"
                               + fileDescriptor.valid());
            
            // will close the file input stream and releases
            // any system resources associated with the
            // stream.
            fileInputStream.close();
        }
        catch (Exception exception) {
            System.out.println(exception.getMessage());
        }
    }
}

輸出:

Is FileDescriptor valid:true

tmp.txt

Note: The programs will run on an online IDE. Please use an offline IDE and change the Name of the file according to your need.




相關用法


注:本文由純淨天空篩選整理自harshsethi2000大神的英文原創作品 FileInputStream getFD() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。