Java FileDescriptor.getFD()方法

原文:https://www.studytonight.com/java-file-io/java-fileinputstream-getfd-method

在本教程中,我们将学习 JavaFileInputStream类的getFD()方法。此方法用于返回文件描述符的对象,该对象表示当前FileInputStream正在使用的文件系统中特定文件的连接。这是一个非静态方法,在 java.io 包中可用。

句法

这是此方法的语法声明。它不接受任何参数,并返回属于当前流的文件描述符对象

public final FileDescriptor getFD()

示例:用 Java 获取文件描述符

在这个例子中,我们使用的是 FileInputStream 类的 getFD()方法,该方法用于在 Java 中获取文件描述符。请看下面的例子。

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();
      }
   }
}

文件中的文本 c:/test.txt

ABCDEF

有效文件:真

示例 2:用 Java 获取文件描述符

在本例中,我们使用的 by using getFD()方法是返回与 Java 中的流链接的文件描述符。请看下面的例子。

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 . file descriptor @ 7 bfcd 12c

结论:

在本教程中,我们学习了 JavaFileInputStream类的getFD()方法,该方法返回文件描述符对象,该对象表示与当前FileInputStream正在使用的文件系统中的确切文件的连接。它只能用类对象访问,如果我们试图用类名访问方法,那么我们会得到一个错误。