关于FileInputStream

FileInputStream 用于读取本地文件中的字节数据,继承自InputStream类

构造方法摘要
FileInputStream(File file)
通过打开一个到实际文件的连接来创建一个FileInputStream,该文件通过文件系统中的 File 对象 file 指定。

FileInputStream(FileDescriptor fdObj)
通过使用文件描述符 fdObj 创建一个FileInputStream,该文件描述符表示到文件系统中某个实际文件的现有连接。

FileInputStream(String name)
通过打开一个到实际文件的连接来创建一个FileInputStream,该文件通过文件系统中的路径名 name 指定。

方法摘要
int available()
返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。

void close()
关闭此文件输入流并释放与此流有关的所有系统资源。

protected void finalize()
确保在不再引用文件输入流时调用其close 方法。

FileChannel getChannel()
返回与此文件输入流有关的唯一FileChannel 对象。

FileDescriptor getFD()
返回表示到文件系统中实际文件的连接的 FileDescriptor 对象,该文件系统正被此FileInputStream 使用。

int read()
从此输入流中读取一个数据字节。

int read(byte[] b)
从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。

int read(byte[] b, int off, int len)
从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。

long skip(long n)
从输入流中跳过并丢弃 n 个字节的数据。

其中read()返回的是读入的一个字节所对应的int值(0-255),而read(byte[] b) 和read(byte[] b, int off, int len) 返回的是读入的字节数

代码实例

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputDemo {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\java\\theTestOnClass\\src\\com\\qst\\IO\\FileInputDemo.java");
            byte[] b = new byte[5];
            //  方法一: int read(byte[] b)
            /*    try {
                while((fis.read(b)) != -1){
                    System.out.print(new String(b));
                    b = new byte[5];
                }
            } catch (IOException e) {
                e.printStackTrace();
            }*/

            // 方法二  int read(byte[] b, int off, int len)
            /*
            try {
                while((fis.read(b, 0, b.length)) != -1){
                    System.out.print(new String(b));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
         */
            //方法三:int read()
            int c = 0;
            try {
                while((c = fis.read()) != -1){
                    System.out.print((char) c);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件不存在!");
        }
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值