IO字节流

IO流

  1. 概述:

    ​ IO流用来处理设备之间的数据传输

    ​ Java对数据的操作是通过流的方式

    ​ Java用于操作的对象都在IO包中 java.io

  2. 分类:

    ​ a:按照数据流向,站在内的角度

    ​ 输入流 读入数据

    ​ 输出流 写出数据

    ​ b:按照数据类型

    ​ 字节流 可以读写任何类型的文件,比如音频,视频,文本文件

    ​ 字符流 只能读写文本文件

  3. IO流基类

    ​ a:字节流的抽象基类

    ​ 字节输入流:InputStream 读

    ​ 字节输出流:OutputStream 写

    ​ b:字符流的抽象基类

    ​ 字符输入流:Reader 读

    ​ 字符输出流:Writer 写

    ​ 注意:由这四个类派生出来的子类名称都是以其父类名作为子类名的后缀

  4. FileOutputStream写出数据

    4.1 构造方法:

    ​ FileOutputStream(File file)

    ​ FileOutputStream(String name)

/*
* 创建字节输出流对象了做了几件事情?
		a:调用系统资源创建a.txt文件
	  	b:创建了一个fos对象
	  	c:把fos对象指向这个文件
	  	
		为什么一定要close()?
		a: 通知系统释放关于管理a.txt文件的资源
		b: 让Io流对象变成垃圾,等待垃圾回收器对其回收
		* */
public class Demo {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("a.txt");
        fos.write("abc".getBytes());
        fos.close();
    }
}
  1. FileOutputStream的三个write()方法

    ​ public void write(int b) 写一个字节,超过一个字节,就砍掉前面的字节

    ​ public void write(byte[] b) 写一个字节数组

    ​ public void write(byte[] b,int off,int len) 写一个字节数组的一部分

  2. FileOutputStream写出数据时的异常处理

public class Demo2 {
    public static void main(String[] args) {
        FileOutputStream out=null;
        try {
             out = new FileOutputStream("b.txt");
            out.write("哈撒给".getBytes());
            out.write("\r\n".getBytes());
            out.write("冲刺".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //释放资源
            try {
                if (out!=null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("aaaaaaa");

    }
}
  1. FileInputStream读取数据的两个read()方法

    ​ int read() 一次读取一个字节,如果没有数据就返回-1

    ​ int read(byte[] b) 一次读取一个字节数组,返回的int类型的值表示读取到字节的个数,没 有数据就返回-1

    两个方法复制文件的比较

public class Copy {
    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream("C:\\Users\\l\\Desktop\\a.txt");
        FileOutputStream out = new FileOutputStream("D:\\a.txt");
       /* int by=0;
        while ((by=in.read())!=-1){
            out.write(by);
            out.flush();
        }
        out.close();
        in.close();
        //很显然一次读写一个字节,来进行文件的复制,效率太低,你应该一次读取一个字节数组,来进行复制。
        */
        byte[] bytes = new byte[1024];
        int len=0;
        while ((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
            out.flush();
        }
        out.close();
        in.close();

    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值