Java教程-Java FileInputStream类

Java FileInputStream类
Java FileInputStream类从文件获取输入字节。它用于读取面向字节的数据(原始字节流),如图像数据、音频、视频等。您也可以读取字符流数据。但是,对于读取字符流,建议使用FileReader类。
Java FileInputStream类声明
让我们看一下java.io.FileInputStream类的声明:
public class FileInputStream extends InputStream
Java FileInputStream类方法
Method | Description |
---|---|
int available() | 它用于返回可以从输入流中读取的估计字节数。 |
int read() | 它用于从输入流中读取数据字节。 |
int read(byte[] b) | 它用于从输入流中读取最多b.length个字节的数据。 |
int read(byte[] b, int off, int len) | 它用于从输入流中读取最多len个字节的数据。 |
long skip(long x) | 它用于跳过并丢弃输入流中的 x 字节数据。 |
FileChannel getChannel() | 它用于返回与文件输入流关联的唯一 FileChannel 对象。 |
FileDescriptor getFD() | 它用于返回FileDescriptor对象。 |
protected void finalize() | 它用于确保在不再引用文件输入流时调用 close 方法。 |
void close() | 它用于关闭流。 |
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