📜  Java I/O-FileInputStream

📅  最后修改于: 2020-09-27 02:00:32             🧑  作者: Mango

Java FileInputStream类

Java FileInputStream类从文件获取输入字节。它用于读取面向字节的数据(原始字节流),例如图像数据,音频,视频等。您还可以读取字符流数据。但是,为了读取字符流,建议使用FileReader类。

Java FileInputStream类声明

让我们看一下java.io.FileInputStream类的声明:

public class FileInputStream extends InputStream

Java FileInputStream类方法

Method Description
int available() It is used to return the estimated number of bytes that can be read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream.
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel getChannel() It is used to return the unique FileChannel object associated with the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is call when there is no more reference to the file input stream.
void close() It is used to closes the stream.

Java FileInputStream示例1:读取单个字符

import java.io.FileInputStream;
public class DataStreamExample {
 public static void main(String args[]){  
  try{  
    FileInputStream fin=new FileInputStream("D:\\testout.txt");  
    int i=fin.read();
    System.out.print((char)i);  

    fin.close();  
  }catch(Exception e){System.out.println(e);}  
 }  
}

注意:在运行代码之前,需要创建一个名为“ testout.txt”的文本文件。在此文件中,我们具有以下内容:

Welcome to javatpoint.

执行完上述程序后,您将从文件中获得一个字符,该字符为87(字节形式)。要查看文本,您需要将其转换为字符。

输出:

W

Java FileInputStream示例2:读取所有字符

package com.javatpoint;

import java.io.FileInputStream;
public class DataStreamExample {
 public static void main(String args[]){  
  try{  
    FileInputStream fin=new FileInputStream("D:\\testout.txt");  
    int i=0;  
    while((i=fin.read())!=-1){  
     System.out.print((char)i);  
    }  
    fin.close();  
  }catch(Exception e){System.out.println(e);}  
 }  
}

输出:

Welcome to javaTpoint