关于io流中的字节输入输出流

输入流就是把电脑磁盘中存储的东西输入到java代码中

package com.qf.a_fileinputstream;

import java.io.*;

public class Demo2 {
    public static void main(String[] args) throws IOException {
        //1.创建一个file对象的  文件抽象
        File file = new File("c:/aaa/1.txt");
        //2.创建字节输入流的核心的类
        FileInputStream fis = new FileInputStream(file);
        //3.加缓冲功能
        BufferedInputStream bis = new BufferedInputStream(fis);
        //4.创建一个数组  缓冲数组
        byte[] buf = new byte[4 * 1024];//4096字节

        /**
         * 5.读取方法
         * public int read(byte[] b)   将文件中的数据 读取到缓冲数组中
         *          throws IOException
         * 从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
         * 重写:
         * read在 InputStream类
         * 参数
         * b - 读取数据的缓冲区。
         * 结果
         * 读入缓冲区的总字节数,如果没有更多的数据,因为文件的结尾已经到达, -1 。
         */
        int length;
        while ((length = bis.read(buf)) != -1) {
            System.out.println(new String(buf, 0, length));
        }
        //6.关闭
        bis.close();
        fis.close();


    }
}

输出流就是从java代码把文件输入到电脑磁盘中

package com.qf.b_fileoutputstream;

import java.io.*;


public class Demo1 {
    public static void main(String[] args) throws IOException {
        //1.创建文件对象
        File file = new File("c:/aaa/2.txt");
        //2.创建核心的字节输出流对象FileOutputStream
        FileOutputStream fos = new FileOutputStream(file);
        //3.加缓冲的效果  BufferedOutputStream
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //4.声明一个字符串
        String str = "abcdefgh";
        /**
         * void	write(byte[] b)  将字节数组中的数据写入到-
         * 将 b.length个字节从指定的字节数组写入此文件输出流。
         */
        //bos.write(str.getBytes());
        /**
         * void	write(byte[] b, int off, int len)
         * 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流。
         */
        //bos.write(str.getBytes(), 0, 3);
        bos.write(1);
        bos.close();
        fos.close();

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值