Java教程

Java FileInputStream

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

Java FileInputStream类声明

让我们看看java.io.FileInputStream类的声明:
public class FileInputStream extends InputStream

Java FileInputStream类方法

方法 说明
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 lidihuo.
执行上述程序后,您将从文件中获取一个字符,该字符为87(字节形式)。要查看文本,您需要将其转换为字符。
输出:
W

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

package com.lidihuo;
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 lidihuo
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4