java第十一天---IO流

一、File文件\文件夹操作

  1、为了通过代码对磁盘中的文件\文件夹进行操作,增删改查

  2、创建File对象格式

    File file=new File("相对路径/绝对路径");

  3、常用方法

     createNewFile():在指位置创建新的文件    mkdir():创建一个新的文件夹    mkdirs():创建多个文件夹    

     delete():删除当前文件或文件夹    canExecute():判断文件/文件夹是否可操作    isFile():判断是否为文件

     isDirectory():判断是否为文件夹    exists():判断路径代表的文件/文件夹是否存在   getAbsolutePath():打印路径,可以直接点击访问

     getParents():得到父目录    list():遍历文件中的所有文件名/文件夹名    listFiles():遍历文件中所有文件名,带绝对路径

  4、示例代码   

public class DemoTest {
    public static void main(String[] args) throws IOException {
        File file = new File("G:/BXJAVAdemo/ss");
//        file.createNewFile();//创建文件
//        file.mkdir();//创建一级文件夹
//        file.mkdirs();//创建多级文件夹
        //以上三个创建方法,运行时如果路径表示的文件/文件夹存在就替换原来的,没有就创建新的
//        file.exists();//判断路径表示的文件或文件夹是否存
//        String absolutePath = file.getAbsolutePath();//得到绝对路径,可以直接点击访问
//        String parent = file.getParent();//得到父级的绝对路径,可以直接点击访问
//        file.delete()//删除当前文件或文件夹,如果是文件夹,里边有子类的话就无法删除
        
/*        File[] files = file.listFiles(); //得到文件夹中的所有子文件的绝对路径
        for (File file1 : files) {
            System.out.println(file1);
        }*/
        String[] list = file.list();//得到文件夹中的所有子文件的名字
        for (String s : list) {
            System.out.println(s);
        }
    }
}
View Code

二、IO流  (输入流和输出流)

  Ⅰ、什么是IO流

    程序中的流是数据从一处移动到另一处,是一连串不间断的数据集合,即使一连串不间断的字节。

  Ⅱ、分类

    按方向:输入流(从硬盘到程序(内存))、输出流(从程序(内存)到硬盘)

    按功能:字节流、字符流

    名字:字节输入流(FileInputStream)、字节输出流(FileOutputStream)、字符输出流(FileWriter)、字符出入流(FileReader)。四大  基流

    其他流:包装流(缓冲流、对象流)、字节转字符流

  Ⅲ、字节流示例

    1、字节输入流  FileInputStream

      常用方法:

        close():关闭字节流    read():从输入流中读取一个字节的数据,读到尾部时返回-1

        read(byte[] b):从输入流读取b.length长度的字节,将字节放置在byte数组中,读取到尾部时返回-1

        read(byte[] b,int off,int len):从输入流中读取len个长度的字符,off是偏移量,从数组的off 下标开始存储

public class InputFD {
    public static void main(String[] args) throws IOException {
//        1、创建通道
        FileInputStream fis = new FileInputStream("G:\\BXJAVAdemo\\ss\\123.txt");
//    上边一行代码的作用:当访问的文件不存在,就先创建,如果存在,直接访问
//        2、读取数据

/*//    ① read();  无参read方法,读取一个字节的数据,读到数据的末尾返回值为 -1
        for(;fis.read()!=-1;){
            System.out.println(fis.read());
        }*/

/*//        ②read(byte[] b) 从输入流一次读取一个byte[]数组长度的字节个数,返回值为读取的字节个数,读取的字节存放在数组中。
//          读到结束返回-1
        byte[] b=new byte[5];
        int len=0;
        for (;(len=fis.read(b))!=-1;){
//        将byte数组转称String字符串
            String s = new String(b,0,len);
            System.out.println(s);
        }*/
//        ③ read(byte[] b,int off,int len) 从输入流中一次读取最多len个字节,从下标off开始存储,其他和②相同
        byte[] b=new byte[8];
        int len=0;
        while ((len=fis.read(b,3,5))!=-1){
            /*System.out.println(len);
            for (byte b1 : b) {
                System.out.println(b1);
            }*/
            String s = new String(b,0,len);
            System.out.println(s);
        }
//        3、关闭通道
        fis.close();

    }
}
View Code

    2、字节输出流  FileOutputStream

      常用方法:

        close():关闭字节流    write():将一个字节写入到输出流中

        write(byte[] b):将一个数组写入到输入流中    write(byte[] b,int off,int len):将一个数组的指定范围写入到输入流

public class OutputFD {
    public static void main(String[] args) throws IOException {
//        1、创建通道
//        FileOutputStream(路径,true/false);  true/false控制是否向文件中原有内容进行追加,默认为false
        FileOutputStream fos = new FileOutputStream("G:\\BXJAVAdemo\\ss\\123.txt",true);
//        2、操作数据

/*//        第一种,向输出流中写入byte数组的数据
        byte[] bytes = new byte[]{'+','d','b','u'};
        fos.write(bytes);*/

//        第二种,write(byte[] b,off,len)向输入流中写入byte数组的数据,可以控制写入的长度。off 读取数组数据的开始位置
//          len 是读取的长度
        String str="+12312312sdfsdf";
        byte[] bytes = str.getBytes();
       fos.write(bytes,0,5);
//        3、关闭通道
        fos.close();
    }
}
View Code

     3、字节缓冲流(BufferInputStream、BufferOutputStream)

      作用:

      缓冲流的作用:提高读写速度。当读或写的时候,如果每读一次就写入一次或者写出一次,太频繁,IO操作是很浪费时间      的,所以就用上了缓冲流,开辟一块缓存区,当读了足够多之后,才进行写入或写出,节省IO操作时间

      常用方法:

       close():关闭管道  读和写的用法就是字节输入、输出流的用法

      构造函数:

        BufferInputStream(InputStream,size);

        BufferInputStream(InputStream);

        BufferOutputStream(OutputStream,size);

        BufferOutputStream(OutputStream);

       size的作用就是给缓冲流的初始化空间大小,不写size的话,有默认值

public class DinnerTest {
    public static void main(String[] args) throws IOException {
//        案例功能:将123.txt的文本复制到456.txt
//        1、打开通道
        FileInputStream fis = new FileInputStream("G:\\BXJAVAdemo\\ss\\123.txt");
        FileOutputStream fos = new FileOutputStream("G:\\BXJAVAdemo\\ss\\456.txt");

//        创建包装缓冲流
        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

//        2、操作数据
         byte[] b=new byte[5];

         while ((bis.read(b))!=-1){
             bos.write(b);
         }
//         3、关闭管道
//         先开后关,后开先关
         bos.close();
         bis.close();
         fos.close();
         fis.close();
    }
}
View Code

  Ⅳ、字符流    

    字符流的底层还是字节流。字符流主要用来处理文本,用字节流处理文本容易出现乱码

    1、字符输入流   FileReader

      常用方法:

        close():关闭管道      read():读取一个字符的数据,读到结束返回-1      

         read(char[] c):读取c.length个字符,存储到字符数组,读到结束返回-1

        read(char[] c,int off,int len):读取len个字符,存储到字符数组中,off为开始存储的起始下标,读到结束返回-1

      示例:

public class DinnerTest {
    public static void main(String[] args) throws IOException {
//        1、打开管道
        FileReader fr = new FileReader("G:\\BXJAVAdemo\\ss\\123.txt");

//        2、操作数据
        char[] c=new char[5];
        int len=0;
        while ((len=fr.read(c))!=-1){
//            System.out.println(c);   c可以直接打印
            String string = new String(c, 0,len);
            System.out.println(string);
        }
        
//        3、关闭通道
        fr.close();
    }
}
View Code

    2、字符输出流     FileWriter

      常用方法:

        close():关闭管道         write():一次写一个字符    write(char[] c):一次写整个c的数据

        write(char[] c,int off,int len):一次写len个字符,从c的off下边开始拿数据写出

      示例:   

public class DinnerTest {
    public static void main(String[] args) throws IOException {
//        将123.txt文本复制到456.txt
//        1、打开管道
        FileReader fr = new FileReader("G:\\BXJAVAdemo\\ss\\123.txt");
        FileWriter fw = new FileWriter("G:\\BXJAVAdemo\\ss\\456.txt");

//        2、操作数据
        char[] c = new char[5];
        int len = 0;
        while ((len = fr.read(c)) != -1) {
            fw.write(c, 0, len);
        }
//        3、关闭通道
        fw.close();
        fr.close();
    }
}
View Code

    3、包装流(字符输出缓冲流、字符输入缓冲流)

      常用方法:

        输出流和输入流的方法分别和字符输出流和字符输入流相似

      示例:

public class DinnerTest {
    public static void main(String[] args) throws IOException {
//        将123.txt文本复制到456.txt
//        1、打开管道
        FileReader fr = new FileReader("G:\\BXJAVAdemo\\ss\\123.txt");
        FileWriter fw = new FileWriter("G:\\BXJAVAdemo\\ss\\456.txt");

//        创建缓冲流
        BufferedReader br = new BufferedReader(fr);
        BufferedWriter bw = new BufferedWriter(fw);

//        2、操作数据
        char[] c = new char[5];
        int len = 0;
        while ((len = br.read(c)) != -1) {
            bw.write(c, 0, len);
        }
//        3、关闭通道
        bw.close();
        br.close();
        fw.close();
        fr.close();
    }
}
View Code

  Ⅴ、转换流(字节转字符)

    1、字节流转字符流  inputStreamReader

      常用方法:

        和所有的写入方法相同

      构造方法:

        InputStreamReader(InputStream in)

      示例:

public class DinnerTest {
    public static void main(String[] args) throws IOException {
//        将123.txt文本复制到456.txt
//        1、打开管道
        FileInputStream fis = new FileInputStream("G:\\BXJAVAdemo\\ss\\123.txt");
        InputStreamReader isr = new InputStreamReader(fis);

//        2、操作数据
        char[] c = new char[5];
        int len = 0;
        while ((len = isr.read(c)) != -1) {
/*            直接打印字符/字节数组的问题:当读取的数据不足填满c时,打印c出来依然显示c.length个字符,
            但是会有问题,你试一下
            所以最好还是使用new  String(char[],off,len)
*/
            System.out.println(c);
        }
//        3、关闭通道
        isr.close();
        fis.close();
    }
}
View Code

    2、字节流转字符流  OutputStreamWriter

      常用方法:

        和所有的写出方法相同

      构造方法:

        OutputStreamWriter(OutputStream out)

      示例:

public class DinnerTest {
    public static void main(String[] args) throws IOException {
//        将123.txt文本复制到456.txt
//        1、打开管道
        FileInputStream fis = new FileInputStream("G:\\BXJAVAdemo\\ss\\123.txt");
        FileOutputStream fos = new FileOutputStream("G:\\BXJAVAdemo\\ss\\456.txt");
//        创建字节流转字符流
        InputStreamReader isr = new InputStreamReader(fis);
        OutputStreamWriter osw = new OutputStreamWriter(fos);

//        2、操作数据
        char[] c = new char[5];
        int len = 0;
        while ((len = isr.read(c)) != -1) {
            osw.write(c,0,len);
        }
//        3、关闭通道
        osw.close();
        isr.close();
        fos.close();
        fis.close();
    }
}
View Code

  Ⅵ、对象流

    作用:

      对象流将对象类序列化后保存在磁盘上。

    什么是序列化?

      序列化就是要将对象状态信息转化成可以传输或存储的形式的过程。

    反序列化?

      重新将序列化后的数据进行加载。

    1、对象写出流   ObjectOutputStream

      在jdk官方文档中,有这样一段话“只有支持java.io.Serializable接口的对象才能写入流中。 每个可序列化对象的类被编码,包    括类的类名和签名,对象的字段和数组的值以及从初始对象引用的任何其他对象的关闭。”,所以,要实现序列化的对象都要实现    Serializable接口。一定要在类中添加序列ID,这样反序列化时才不会出现错误

      常用方法:

        writeObject(Object obj):将指定的对象写入ObjectOutputStream。

        close():关闭通道

      构造方法:

        ObjectOutputStream(OutputStream os)

      示例:

import java.io.Serializable;

public class Person implements Serializable {
    private static final long serialVersionUID = 778918558423652605L;
        String name;
        int age;
        String address;

    public Person(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }
}
View Code
public class DinnerTest {
    public static void main(String[] args) throws IOException {
//        将Person类序列化后写道123.txt
//        1、打开管道
        FileOutputStream fos = new FileOutputStream("G:\\BXJAVAdemo\\ss\\123.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);

//        2、处理数据
        Person person = new Person("小红", 12, "钓鱼岛");
        oos.writeObject(person);

//        3、关闭通道
        oos.close();
        fos.close();
    }
}
View Code

    2、对象读入流    ObjectInputStream

      常用方法:

        readObject():读取ObjectInputStream对象中的数据

      构造函数:

         ObjectInputStream(InputStream is)

      示例:

public class DinnerTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
//          将123.txt的对象信息读取进来
//        1、打开管道
        FileInputStream fis = new FileInputStream("G:\\BXJAVAdemo\\ss\\123.txt");
//        创建对象输入流
        ObjectInputStream ois = new ObjectInputStream(fis);

//        2、处理数据
        Object o = ois.readObject();
        Person p=(Person)o;
        System.out.println(p.name+","+p.age+","+p.address);
//        3、关闭通道
        ois.close();
        fis.close();
    }
}
View Code

   Ⅶ、IO异常处理方式

public class ExceptionHandler {
    public static void main(String[] args) {
//        首先提升作用域
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;
        try {
//            FileInputStream、FileOutputStream两个都可能会出现“FileNotFoundException”异常
            fileInputStream = new FileInputStream("G:\\BXJAVAdemo\\ss\\123.txt");
            fileOutputStream = new FileOutputStream("G:\\BXJAVAdemo\\ss\\123.txt");

//           read()、write可能出现IOException异常
            int read = fileInputStream.read();
            while (read!=-1){
                fileOutputStream.write(read);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
//            finally放置一定会执行的代码,但是判断两个流对象是否为null,如果为空,则会出现空指针异常,所以先判断是否为空。
//            两个close()分开写的原因:不会因为第一个不能执行,而导致第二个close方法也无法执行
            try {
                if(fileOutputStream!=null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(fileInputStream!=null){
                        fileInputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
View Code

 

posted @ 2020-12-18 21:36  橙汁one  阅读(76)  评论(0编辑  收藏  举报