IO流(1)--字节流

  • IO流分类:

    流向:
    输入流
    输出流
    数据类型:
    1.字节流
    字节输入流
    字节输出流
    2.字符流
    字符输入流
    字符输出流

字节输入流:
具体操作步骤:
字节输入流操作步骤:
A:创建字节输入流对象
FileInputStream fis = new FileInputStream(“a.txt”);

B:调用方法读取数据
一次读取一个字节:read()

C:释放资源
fis.close

& FileOutputStream fos = new FileOutputStream(“fos.txt”);
请问上面这个操作做了哪几件事情?
1.创建了一个文件输出流fos,指向文件a.txt
2.创建了a.txt这个文件

输出演示:

public class OutputStreamExercise {

    /**
     * 需求:请用字节流往一个文本文件中写一句话:"helloworld"。
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        FileOutputStream fos = new FileOutputStream("a.txt");

        //调用输出流的写数据的方法给文件中写数据
        String s="helloworld";
        byte[] bs = s.getBytes();
        fos.write(bs);

        //释放资源,关流操作
                fos.close();
    }

输入演示:

public class InputStreamExercise {

    /**
     * A:创建字节输入流对象
     FileInputStream  fis = new FileInputStream("a.txt");

     * B:调用方法读取数据
     一次读取一个字节:read()

     * C:释放资源
     fis.close
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        FileInputStream fis = new FileInputStream("a.txt");


        int a;
        while((a=fis.read())!=-1){
            System.out.println((char)a);
        }

        fis.close();
    }

}

练习:复制一个图片文件

public class CopyExercise {

    /**
     * 复制一个图片
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        FileInputStream fis = new FileInputStream("E://KanKan//W020080220354931747530.jpg");
        FileOutputStream fos = new FileOutputStream("c.jpg");

        //一次读写一个字节数组
        byte[] bys =  new byte[1024];
        int len;
        while((len=fis.read(bys))!=-1){
            fos.write(bys, 0, len);
        }

        fis.close();
        fos.close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值