第九章字节流 FileInputStream、FileOutputStream

1.字节流

在计算机中,无论是文本、图片、音频还是视频,所有文件都是以二进制(字节)形式存在的,I/O流中 针对字节的输入/输出提供了一系列的流,统称为字节流

以内存为中心(对象)

2.FileInputStream/FileOutStream方法

FileInputStream

OutputStream输出流 

以内存为参照 从内存输出(Output)到磁盘文件  ( 实现程序数据到磁盘文件,写文件 ) OutputStream是以字节为单位的输出流的超类,提供了write()函数从输出流中读取字节数据。

3.代码功能

//读出每次读取一个字节

//读出每次读取一个字节
 FileInputStream read = new FileInputStream(file);
        int b = 0 ;
        while ((b = read.read()) != -1 ){
            System.out.println((char)b);
        }

指定字节读出

var fos = new FileOutputStream(file);
var fis = new FileInputStream(file);
fos.write("hello123".getBytes());

byte[] buf = new byte[10];
int len = fis.read(buf,2,3);

System.out.println(Arrays.toString(buf));
System.out.println(fis.read());


//按照指定字节读写文件
FileInputStream fileInputStream = new FileInputStream(realPath);
ServletOutputStream outputStream = resp.getOutputStream();
        byte[] bytes = new byte[1024 * 1024 *8 ];
        int len = 0;
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
 outputStream.close();
 fileInputStream.close();

全部读完

byte[] bytes =  fis.readAllBytes();
       String str = new String(bytes);
       System.out.println(str);

读取一个文件中代码行数字

 public static long count (File file) throws IOException {
        long count = 0;
        FileInputStream fie = new  FileInputStream(file);
        String str = new String(fie .readAllBytes());
        count = str.lines().count();
        fie.close();
        return  count;
    }

4.作业

1、编写一个方法,是不是两个文件是不是一个文件。

2、编写一个方法,识别这个文件的真实格式。(选做)

3、编写一个方法实现文件拷贝。

4、编写一个方法实现目录拷贝。

5、统计一个文件有多少行代码?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值