Java IO流(三)FileInputStream

简介

FileInputStream 主要用于从一个文件系统读取字节,建议读取raw bytes,例如图片,如果需要读取字符建议使用 FileReader。

构造方法

FileInputStream(String name)

从一个字符串路径中读取数据

FileInputStream(File file)

从一个文件对象中读取数据

常用方法

read()
每次只读取一个字节
read(byte[] b)
读取b.length个字节,返回读取自己的个数
read(byte[] b, int off, int len)

close()

代码

read()方法使用

public class Demo06 {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("a.txt");
        int read;
        while ((read = fileInputStream.read()) != -1)
        {
            System.out.print((char)read);
        }
        fileInputStream.close();

    }
}

read(byte[] b)

public class Demo07 {
    public static void main(String[] args) throws IOException {

        FileInputStream fileInputStream = new FileInputStream("a.txt");
        byte[] bytes = new byte[2];
        int read = fileInputStream.read(bytes);
        String string = new String(bytes);
        System.out.println(string);
        fileInputStream.close();

    }
}
public class Demo07 {
    public static void main(String[] args) throws IOException {

        FileInputStream fileInputStream = new FileInputStream("a.txt");
        byte[] bytes = new byte[1024];
        int read;

        while ((read = fileInputStream.read(bytes)) != -1)
        {
            System.out.println(new String(bytes, 0, read));
        }

        fileInputStream.close();

    }
}

扩展

String(byte[] bytes)

把一个字节数组作为参数,实例化字符串

String(byte[] bytes, int offset, int length)

从一个字节数组中读取指定长度字节实例化为字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值