字节流+案例

字节流

字节流的父类(抽象类)

  • InputStream 字节输入流

    • public int read(){}

    • public int read(byte[] b){}

    • public int read(byte[] b, int off, int len){}

  • OutputStream字节输入流

    • public void write(int n){}

    • public void write(byte[] b){}

    • public void write(byte[] b, int off, int len){}

FileInputStream 文件输出流

/**
 * 演示FileInputStream的使用
 * */
public class Demo1 {
    public static void main(String[] args) throws Exception {
        //1创建FileInputStream,并指定文件路径
        FileInputStream fis = new FileInputStream("e:\\aaa.txt");
        //2读取文件
        //2.1单个字节读取
        //fis.read();//只读一个字节,需要通过遍历来打印所有
//        int data = 0;
//        while((data = fis.read()) != -1){
//            System.out.print((char)data);//打印的时ascii
//        }
        //2.2一次读取多个字节
//        byte[] buf = new byte[3];  //创建一个容量是3的数组

//        int count = fis.read(buf);           //没存读取3个,不是最优的,需要用循环
//        System.out.println(new String(buf));
//        System.out.println(count);
        byte[] buf2 = new byte[1024];  //容量可以创建大一点,这样一次性就读完了
        int count = 0;
        while ((count = fis.read(buf2)) !=-1){
            System.out.println(new String(buf2,0,count)); //count就是实际读取的字节数
        }
        //3关闭
        fis.close();;
        System.out.println("执行完毕");
    }
}

FileOutputStream 文件输入流

/**
 * 演示文件字节输出流的使用
 * FileOutputStream
 * */
public class Demo2 {
    public static void main(String[] args) throws IOException {
        //1创建文件输出流对象
        FileOutputStream fos = new FileOutputStream("e:\\aaa.txt",true);//同一个文件,每一次运行添加的内容都会重写上一次的内容。加上true后,每次添加的内容都会接着上次的内容。
        //写入文件
        fos.write(97);
        fos.write('b');
        fos.write('c');
        String string = "helloword!";
        fos.write(string.getBytes());
        //3关闭
        fos.close();
        System.out.println("执行完毕");
    }
}
使用文件字节流实现文件的复制
/**
 * 使用文件字节流实现文件的复制
 * */
public class Demo3 {
    public static void main(String[] args) throws Exception {
        //1创建流
        //1.1文件字节输入流
        FileInputStream fis = new FileInputStream("e://aaa.txt");
        //1.2文件字节输出流
        FileOutputStream fos = new FileOutputStream("e://bbb.txt");
        //2一边读,一边写
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = fis.read(buf))!=-1){
            fos.write(buf,0,count);
        }
        //3关闭
        fis.close();
        fos.close();
        System.out.println("复制完毕");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值