InputStream和OutputStream的基本使用

一、FileInputStream:字节输入流

        实例化了inputStream

构造方法: 

1.创建一个FileInputStream:

(1)new FileInputStream(String)

(2)new FileInputStream(File对象)

       //(1)构造方法1:FileInputStream(String)
        InputStream fis = new FileInputStream("E:\\Apesource\\Java\\Text\\text.txt");
        System.out.println(fis);

        //(2)构造方法2:FileInputStream(File)
        File path = new File("E:\\Apesource\\Java\\Text\\text.txt");
        InputStream inputStream2 = new FileInputStream(path)

2.读取内容方法:

(1)read(int)

(2)read(byte[])

        //(1)read()
        int len;
        while ((len = fis.read()) !=-1){
            System.out.println((char)len);
        }
        //(2)read(byte[])
        byte[] b = new byte[1024];
        int i;

        while ((i = fis.read(b)) != -1){
            System.out.println("长度 " + i);
            System.out.println("内容 " + new String(b));
            System.out.println("内容 " + b);
            System.out.println("------------------------");
        }

(3)通过缓冲流

        FileInputStream fis = new FileInputStream("E:\\Apesource\\Java\\Text\\text.txt");
        //创建BufferedInputStream缓冲流 构造方法传入FileInputStream
        BufferedInputStream bis = new BufferedInputStream(fis);

        //每次从缓冲区读取5个字节
        byte[] buf = new byte[5];
        int len;

        //循环读取缓冲区的内容
        while ((len = bis.read(buf)) != -1) {

            System.out.println(new java.lang.String(buf, 0, len));
            System.out.print(len);
        }

 二、FileOutputStream:字节输出流

        创建的方式同上FileInputStream

构造方法: 

1.写入磁盘的方法:

(1)write(int):

        写入磁盘的内容为对应的ASCALL码对象的图标

(2)write(byte[]):

        写入磁盘字符类型的数组

        //(1)write(int)
        File file = new File("E:\\Apesource\\Java\\Text\\text2.txt");
        //参数1:目标路径
        //参数2:是否追加,true,在原来的磁盘文件的末尾写内容
        FileOutputStream fos = new FileOutputStream(file,true);
        fos.write(97);//a
        fos.write(98);//b

        //(2)write(bytr[])
        byte[] b = "This is a Cat".getBytes();
        fos.write(b);

(3)BufferedOutputStream:

      字符输出缓冲流

        //字符输出缓冲流 buffered--缓存
        File file = new File("E:\\Apesource\\Java\\Text\\text3.txt");
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        bos.write(97);
        bos.write("i am spiderman".getBytes());
        bos.write("i am ironman".getBytes(), 3, 1);

        bos.close();
        fos.close();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值