Java FileInputStream.close()方法

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

在本教程中,我们将学习 JavaFileInputStream类的close()方法。此方法用于关闭当前FileInputStream,并释放与此流链接的所有系统资源。这是一个非静态方法,在 java.io 包中可用。

句法

这是此方法的语法声明。它不接受任何参数,也不返回值。

public void close()

示例 1:在 Java 中关闭FileInputStream

我们可以使用 FileInputStream 的 close()方法来关闭 Java 中文件的实例。见下面的例子。

package com.studytonight;
import java.io.IOException;
import java.io.FileInputStream;
public class FileInputStreamDemo {
   public static void main(String[] args) throws IOException {
      FileInputStream fis = null;
      int i = 0;
      char c;      
      try {
         // create new file input stream
         fis = new FileInputStream("E://studytonight//output.txt");         
         // read byte from file input stream
         i = fis.read();         
         // convert integer from character
         c = (char)i;         
         // print character
         System.out.println(c);         
         // close file input stream
         fis.close();
         System.out.println("Close() invoked");         
         // tries to read byte from close file input stream
         i = fis.read();
         c = (char)i;
         System.out.println(c);

      } catch(Exception ex) {
         // if an I/O error occurs
         System.out.println("IOException: close called before read()");
      } finally {
         // releases all system resources from the streams
         if(fis!=null) {
            fis.close();
         }
      }
   }
}

IOException:读取前调用关闭()

输出. txt

ABCDEF

示例 2:在 Java 中关闭FileInputStream

在本例中,我们在从流中读取数据之前关闭了该流,因此与它相关的所有资源都将被删除。如果我们试图在关闭流后读取数据,它将抛出一个异常java.io.IOException: Stream closed

import java.io.*;
public class CloseOfFIS {
 public static void main(String[] args) throws Exception {
  FileInputStream fis_stm = null;
  int count = 0;
  try {
   // Instantiates FileInputStream
   fis_stm = new FileInputStream("E://studytonight//output.txt");
   // By using read() method is to read
   // a byte from fis_stm
   count = fis_stm.read();
   // Display corresponding bytes value
   byte b = (byte) count;
   // Display value of b
   System.out.println("fis_stm.read(): " + b);
   // By using close() method is to close
   // close the stream     
   fis_stm.close();
   // when we call read() method after
   // closing the stream will result an exception
   count = fis_stm.read();

  } 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 . read():0 Java . io . io 异常:流关闭

结论

在本教程中,我们学习了 JavaFileInputStream类的close()方法。此方法在被调用时将关闭当前流,并且不能对其执行进一步的操作。