java基础IO流

IO

  • 可以将数据从本地文件读取出来
  • 可以将数据从内存保存到本地文件

概述

  • I表示input,是数据从硬盘进内存的过程,称之为读。
  • O表示output,是数据从内存到硬盘的过程,称之为写。
  • IO的数据传输,可以看作是一种数据的流动,按照流动的方向,以内存为参照物,进行读写操作

IO流的分类

按流向分

  • 输入流
  • 输出流

按数据类型分

  • 字节流:操作所有类型的文件,包括音频视频图片等
  • 字符流:只能操作纯文本文件,包括Java文件,txt文件等

注:

  • 纯文本文件:用记事本打开能读的懂,那么这样的文件就是纯文本文件
  • 如果想要拷贝,一律使用字节流或者字节缓冲流
  • 想要把文本文件中的数据读到内存中,请使用字符输入流
  • 想要把内存中的数据写道文本文件中,请使用字符输出流
  • GBK码表中一个中文俩个字节,UTF-8编码格式一个中文3个字节

字节流

输出流 FileOutputStream

构造方法

  • FileOutputStream(File file) 创建文件输出流以写入由指定的 File对象表示的文件。  
  • FileOutputStream(File file, boolean append) 创建文件输出流以写入由指定的 File对象表示的文件。  
  • FileOutputStream(FileDescriptor fdObj) 创建文件输出流以写入指定的文件描述符,表示与文件系统中实际文件的现有连接。  
  • FileOutputStream(String name) 创建文件输出流以指定的名称写入文件。  
  • FileOutputStream(String name, boolean append) 创建文件输出流以指定的名称写入文件。

注意事项

1.如果文件不存在,它会帮我们自动创建出来
2.如果文件存在,会把文件清空

常用方法

  • public void write(int b):将指定的字节写入此文件输出流。
    注:传递一个整数时,那么实际上写入文件中的,是这个整数在码表中对应的那个字符
  • public void close():关闭此文件输出流并释放与此流相关联的任何系统资源。
    注:每次使用完流必须要释放资源

public class OutputDemo2 {
    public static void main(String[] args) throws IOException {
        // 创建字节输出流的对象
        FileOutputStream fos = new FileOutputStream("D:\\FileTest\\b.txt");
        // FileOutputStream fos = new FileOutputStream(new File("D:\\FileTest\\a.txt"));

        // 写数据
        fos.write(97);

        // 释放数据
        fos.close();
    }
}

写入数据的三种方式

  • public void write(int b):一次写入一个字节
  • public void write(byte[] b):一次写一个字节数组数据
  • public void write(byte[] b,int off ,int len):一次写一个字节数组的部分数据。len是表示几个
public class OutputDemo3 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("D:\\FileTest\\a.txt");

        // byte[] bys = {97,98,99};
        // fos.write(bys);

        byte[] bys = {97,98,99,100,101,102,103,104,105};
        fos.write(bys,2,5);
        fos.close();
    }
}

字节流实现换行和追加

  • 写完数据和,加换行符。windows:\r\n,linux:\n,mac:\r
    public class OutputDemo5 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("D:\\FileTest\\b.txt");
        fos.write(97);
        fos.write("\r\n".getBytes());
        fos.write(98);
        fos.write("\r\n".getBytes());
        fos.write(99);
        fos.write("\r\n".getBytes());
        fos.write(100);
        fos.write("\r\n".getBytes());
        fos.write(101);
        fos.write("\r\n".getBytes());
        fos.close();
    }
    }

    追加

  • FileOutputStream(String name, boolean append) 创建文件输出流以指定的名称写入文件。
  • FileOutputStream(File file, boolean append) 创建文件输出流以写入由指定的 File对象表示的文件。
    这俩个构造方法的第二个参数表示是否续写,如果为true则继续添加不删除原先文件的内容
    public class OutputDemo5 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("D:\\FileTest\\b.txt",true);
        fos.write(97);
        fos.write("\r\n".getBytes());
        fos.write(98);
        fos.write("\r\n".getBytes());
        fos.write(99);
        fos.write("\r\n".getBytes());
        fos.write(100);
        fos.write("\r\n".getBytes());
        fos.write(101);
        fos.write("\r\n".getBytes());
        fos.close();
    }
    }

##### 注
String里面由一个getBytes()方法可以把字符串转换成字符数组

### 输入流  FileInputStream

#### 构造方法
- `FileInputStream(File file)` 通过打开与实际文件的连接创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。 
- `FileInputStream(FileDescriptor fdObj)` 创建 FileInputStream通过使用文件描述符 fdObj ,其表示在文件系统中的现有连接到一个实际的文件。  
- `FileInputStream(String name)` 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。  
```Java
public class InputDemo1 {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("D:\\FileTest\\a.txt");
            int read = fileInputStream.read();
            System.out.println(read);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  • 如果文件不存在就会报错

读入多个字节

public class InputDemo2 {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("D:\\FileTest\\a.txt");
            int b;
            while ((b = fileInputStream.read()) != -1){
                System.out.print((char)b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally { 
            if (fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

常用方法

  • public int read()从该输入流读取一个字节的数据。如果想看到对应字符,要强转成char

提高拷贝速度的方法

字节流通过创建字节数组,可以一次读写多个数据。

  • public int read(byte[] b):从输入流读取最多b.length个字节数据
    返回的是读入缓冲区的总字节数,也就是实际读取字节个数
    public class Test2 {
    public static void main(String[] args) {
        FileInputStream fis= null;
        FileOutputStream fos = null;
        try {
            fis= new FileInputStream("D:\\FileTest\\01.mp4");
            fos = new FileOutputStream("D:\\FileTest\\copy\\01.mp4");
            byte[] bytes = new byte[1024];
            int len; // 本次读到的有效字节个数 -- 这次读了几个字节
            while ((len=fis.read(bytes))!=-1){
                fos.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null){
                    fis.close();
                }
                if (fos != null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }

### 字节流异常处理
使用try...catch捕获异常,用finally来关闭IO流
```Java
public class OutputDemo5 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("D:\\FileTest\\b.txt",true);
            fos.write(97);
            fos.write("\r\n".getBytes());
            fos.write(98);
            fos.write("\r\n".getBytes());
            fos.write(99);
            fos.write("\r\n".getBytes());
            fos.write(100);
            fos.write("\r\n".getBytes());
            fos.write(101);
            fos.write("\r\n".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
} 

缓冲流

缓冲流是为了提供效率的,不能直接操作文件,需要传递字节流

字节缓存流

  • BufferOutputStream:字节缓冲输出流
  • BufferedInputStream:字节缓存输入流

构造方法:

  • 字节缓冲输出流:BufferedOutPutStream(OutputStream out)
  • 字节缓冲输入流:BufferedInputStream(InputStream in)

字节缓冲流仅仅是提供缓冲区,而真正的读写数据还得以考基本的字节流对象进行操作

一次读取一个字节

public class BufferInputDemo {
    public static void main(String[] args) throws IOException {
        // 创建字节缓冲输入流
        // 在底层创建了一个默认长度为8192的字节数组。
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\FileTest\\1.mp4"));

        // 创建字节缓冲输出流
        // 在底层创建了一个默认长度为8192的字节数组。
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\FileTest\\copy\\1.mp4"));

        int b;
        while ((b = bis.read()) != -1){
            bos.write(b);
        }

        // 方法的底层会把字节流关闭
        bis.close();
        bos.close();
    }
}

一次读取一个字节数组

public class BufferDemo2 {
    public static void main(String[] args) throws IOException {
        // 创建字节缓冲输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\FileTest\\1.mp4"));

        // 创建字节缓冲输出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\FileTest\\copy\\2.mp4"));

        byte[] bs = new byte[1024];

        int len;

        while ((len=bis.read(bs))!=-1){
            bos.write(bs,0,len);
        }

        bis.close();
        bos.close();z
    }
}

字符流

  • 字节流读取文件,读到内存中,有可能出现乱码,导致写入的时候也可能出现乱码

    概述

  • 字符流 = 字节流 + 编码表
  • 不管在什么表中,中文的第一个字节一定是负数

注意事项

  • WIndows默认使用码表为:GBK,一个字符俩个字节
  • idea和以后工作默认使用Unicaode的UTF-8编码格式,一个中文三个字符

编码

  • byte[] getBytes():使用平台默认字符集将改String编码为一系列字节,将结构存储到新的字节数组中
  • byte[] getBytes(String charsetName):使用指定的字符集将改String编码为一系列字节,将结构存储到新的字节数组中

解码

  • String(byte[] bytes):通过使用平台默认字符集解码指定的字节数组来构造新的String
  • String(byte[] bytes,String charsetName):通过指定的字符集解码指定的字节数组来构造新的String
public class CharStreamDemo2 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        // byte[] getBytes():使用平台默认字符集将改String编码为一系列字节,将结构存储到新的字节数组中
        // byte[] getBytes(String charsetName):使用指定的字符集将改String编码为一系列字节,将结构存储到新的字节数组中

        String s = "学习笔记";
        byte[] bytes = s.getBytes(); // 默认UTF-8
        System.out.println(Arrays.toString(bytes));

//        byte[] bytes1 = s.getBytes("UTF-8");
        byte[] bytes1 = s.getBytes("GBK");
        System.out.println(Arrays.toString(bytes1));

        // String(byte[] bytes):通过使用平台默认字符集解码指定的字节数组来构造新的String

        String str = new String(bytes);
        System.out.println(str);
        // String(byte[] bytes,String charsetName):通过指定的字符集解码指定的字节数组来构造新的String
        String str2 = new String(bytes1,"GBK");
        System.out.println(str2);
    }
}

输出流 FileWriter

构造方法

FileWriter(File file) 给一个File对象构造一个FileWriter对象。
FileWriter(File file, boolean append) 给一个File对象构造一个FileWriter对象。
FileWriter(FileDescriptor fd) 构造与文件描述符关联的FileWriter对象。
FileWriter(String fileName) 构造一个给定文件名的FileWriter对象。
FileWriter(String fileName, boolean append) 构造一个FileWriter对象,给出一个带有布尔值的文件名,表示是否附加写入的数据。

常用方法

void write(int c)写一个字符
void write(char[] cbuf)写出一个字符数组
void write(char[ cbuf, int off, int len)写出字符数组的一部分
void write(String str)写一个字符串
void write(String str, int off, int len)写一个字符串的一部分

public class CharStreamDemo3 {
    public static void main(String[] args) throws IOException {

        // 创建字符输出流
        // FileWriter fw = new FileWriter(new File("D:\\FileTest\\c.txt"));
        FileWriter fw2 = new FileWriter("D:\\FileTest\\c.txt");

        // 写出数据
        //`void write(int c)`写一个字符
        fw2.write(97);
        fw2.write(98);
        fw2.write(99);

        //`void write(char[] cbuf)`写出一个字符数组
        char[] chars = {97,98,99,100,101,102};
        fw2.write(chars);

        //`void write(char[ cbuf, int off, int len)`写出字符数组的一部分
        fw2.write(chars,1,3);

        //`void write(String str)`写一个字符串
        fw2.write("学习笔记");

        //`void write(String str, int off, int len)`写一个字符串的一部分
        fw2.write("学习笔记的一部分",2,6);

        fw2.close();

    }
}

注意事项

  1. 如果文件不存在,就创建。但是要保证父级路径存储。
  2. 如果文件存在就清空
  3. 写出int类型的整数,实际写出的是整数在码表上对应的字符。
  4. 写出字符串数据,是吧字符串本身原样写出。
  5. 每次使用完流必须要释放资源。

特殊方法

  • flush():刷新流,还可以继续写数据
  • close():关闭流,释放资源。但是在关闭之前会先刷新流。一旦关闭,就不能在写数据

FileReader

构造方法

FileReader(File file)新的 FileReader ,给出 File读取。
FileReader(FileDescriptor fd)一个新的 FileReader ,给定 FileDescriptor读取。
FileReader(String fileName)一个新的 FileReader ,给定要读取的文件的名称。  

public class CharStreamDemo5 {
    public static void main(String[] args) throws IOException {
//        FileReader fr = new FileReader(new File("D:\\FileTest\\e.txt"));
        FileReader fr = new FileReader("D:\\FileTest\\e.txt");

        // 读取数据
        // 一次读取一个字节
        int ch;
        while ((ch= fr.read())!= -1){
            System.out.print((char) ch);
        }

        fr.close();
    }
}
public class CharStreamDemo6 {
    public static void main(String[] args) throws IOException {
        // 一次读取多个字符
        FileReader fr = new FileReader("D:\\FileTest\\e.txt");

        // 读取数据
        int len;
        char[] chars = new char[1025];
        while ((len= fr.read(chars))!= -1){
            System.out.print(new String(chars,0,len));
        }

        fr.close();
    }
}

字符缓冲流

  • BufferedWriter:可以将数据高效的写出
  • BufferedReader:可以将数据高效的读取到内存
public class CharStreamDemo7 {
    public static void main(String[] args) throws IOException {
        // 字符缓冲输入流
        BufferedReader br = new BufferedReader(new FileReader("D:\\FileTest\\test.txt"));

        // 读取数据
        char[] chars = new char[1024];
        int len;
        while ((len=br.read(chars))!=-1){
            System.out.println(new String(chars,0,len));
        }
        br.close();
    }
}
public class CharStreamDemo8 {
    public static void main(String[] args) throws IOException {
        // 字符缓冲输出流
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\FileTest\\a.txt"));

        // 写出数据
        bw.write(97);
        char [] chars = {98,99,100};
        bw.write(chars);

        bw.write(chars,2,1);

        bw.write("自学笔记");

        String test = "123456测试";
        bw.write(test,2,5);
        bw.flush();
        bw.close();
    }
}

特有功能

BufferedWriter

  • void newLine():写一行行分隔符,行分隔符字符串由系统属性定义

BufferedReader

  • public String readLine():读一行文件。结构包括行的内容的字符串,不包括任何终止字符串,如果流的结尾已经到达,则返回null
public class CharStreamDemo9 {
    public static void main(String[] args) throws IOException {
        // void newLine():写一行行分隔符,行分隔符字符串由系统属性定义
        BufferedWriter bw  = new BufferedWriter(new FileWriter("D:\\FileTest\\a.txt"));

        // 写出数据
        bw.write("测试换行");
        bw.newLine();
        bw.write("12312421");
        bw.newLine();
        bw.flush();
        bw.close();

    }
}
public class CharStreamDemo10 {
    public static void main(String[] args) throws IOException {
        // public String readLine():读一行文件。结构包括行的内容的字符串,不包括任何终止字符串,如果流的结尾已经到达,则返回null

        BufferedReader br = new BufferedReader(new FileReader("D:\\FileTest\\a.txt"));

        // 读取数据
        String line;
        while ((line = br.readLine())!=null){
            System.out.println(line);
        }
        br.close();
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值