13.IO流

File类的使用

1.File类的理解

  • 1.File类的一个对象,代表一个文件或一个文件目录(俗称文件夹)
  • 2.File类声明在Java.io包下
  • 3.File类中涉及到关于文件或文件目录的创建删除重命名修改时间文件大小等方法
  • 如果需要读取或写入文件内容,必须使用IO流来完成
  • 4.后续File类的对象常会作为参数传递给流的构造器中,指明读取或写入的”终点“

2.File的实例化

2.1常用构造器

File(String filePath)
File(String parentPath,String childPath)
File(File parentFile,String childPath)

2.2路径的分类

相对路径:相较于某个路径下的,指明的路径

绝对路径:包含盘符在内的文件或文件目录的路径

(Idea中)说明:

​ 如果开发使用JUnit中的单元测试方法,相对路径即为当前Module下

​ 如果使用main()方法测试,相对路径即为当前的Project下

(Eclipse)说明:

​ 不管哪种测试,相对路径都是当前的Project下

2.3路径分隔符

windows:\\
unix:/

3.File类的常用方法

获取功能 getAbsolutePath() getParent()

public String getAbsolutePath():获取绝对路径
public String getPath():获取路径
public String getName():获取名称
public String getParent():获取上层文件目录路径,若无,返回null
public long length():获取文件长度(即:字节数)。不能获取目录的长度
public long lastModified():获取最后一次的修改时间,毫秒值

pubic String[] list():获取指定目录下的所有文件活着文件目录的名称数组
public File[] listFiles():获取指定目录下的所有文件或者文件目录的File数组

重命名功能

public void renameTo(File dest):把文件重命名为指定的文件路径
要想保证返回true,需要file1在硬盘中是存在的,且file2不能再硬盘中存在

判断功能 isDirectory() isFile() exists()

public boolean isDirectory():判断是否是文件目录
public boolean isFile():判断是否是文件
public boolean exists():判断是否存在
public boolean canRead():判断是否可读
public boolean canWrite():判断是否可写
public boolean isHidden():判断是否隐藏

创建功能 creatNewFile()

创建硬盘中对应的文件或文件目录
public boolean creatNewFile():创建文件,若文件存在,则不创建,返回false
public boolean mkdir():创建文件目录,如果文件目录存在,就不创建。如果此文件
目录的上层目录不存在,也不创建
public boolean mkdirs():创建文件目录,如果上层文件目录不存在,一并创建

删除功能

public boolean delete():删除文件或者文件夹
注意:java的删除不走回收站

IO流概述

一、流的分类

1.操作数据单位:字节流、字符流

2.数据的流向:输入流、输出流

3.流的角色: 节点流、处理流

二、流的体系结构

抽象基类:节点流(文件流):缓冲流(处理流的一种):
InputStreamFileInputStream (read(byte[] cbuf))BufferedInputStream (read(byte[] cbuf))
OutputStreamFileOutputStream (writer(byte[] cbuf,0,len)BufferedOutputStream (writer(byte[] cbuf,0,len)
ReaderFileReader (read(char[] cbuf))BufferedReader (read(char[] cbuf)/readLine():每行但不会自动换行)
WriterFileWriter (writer(char[] cbuf,0,len)BufferedWriter (writer(char[] cbuf,0,len)

三、输入输出的标准化过程

输入过程

1.File类的实例化

2.流的实例化

3.读入的操作

​ byte[]或char[]

4.资源关闭

try -catch-finally来处理异常

输出过程

1.File类的实例化

2.流的实例化

3.写出的操作

​ write(char[]/byte[] buffer,0,len)

4.资源关闭

try -catch-finally来处理异常

节点流(或文件流)

FileReader

 /*
    1.将hello.txt文件内容读入到程序中,并输出到控制台
    2.异常处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally处理
    3.读入的文件一定要存在,否则报错FileNotFoundException
    * */
    @Test
    public void testFIleReader()  {
        FileReader fr= null;
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");//相较于当前module
            //2.提供具体的流
            fr = new FileReader(file);
            //3.数据的读入
            //read():返回读入的一个字符,如果达到文件末尾,则返回-1
//        int data = fr.read();
//        while(data!=-1){
//            System.out.print((char)data);
//            data=fr.read();
//        }
            int data;
            while((data=fr.read())!=-1){
                System.out.print((char) data);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //4.流的关闭
            try {
                if(fr!=null) {
                    fr.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
@Test
    public void testFileReader1(){
        FileReader fr = null;
        try {
            //1.File类的实例化
            File file = new File("hello.txt");
            //2.FileReader流的实例化
            fr = new FileReader(file);
            //3.读入的操作
            //read(cahr[] cbuf):返回每次读入cbuf数组中的字符的个数,如果达到文件末尾,返回-1
            char[] cbuffer=new char[5];
            int len;
            while((len=fr.read(cbuffer))!=-1){
                //错误
    //            for (int i = 0; i < cbuffer.length; i++) {
    //                System.out.print(cbuffer[i]);
    //            }
                //正确的
//                for (int i = 0; i < len; i++) {
//                    System.out.print(cbuffer[i]);
//                }
                //错误
//                String str=new String(cbuffer);
//                System.out.print(str);
                //正确
                String str=new String(cbuffer,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(fr!=null) {
                //4.资源关闭
                try {
                    fr.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

FileWriter

/*
从内容中写入数据到硬盘的文件里
说明:
    1.输出操作,对应的File可以不存在的
    2.File对应的硬盘中的文件不存在,自动创建此文件
    存在的话:
            流的构造器是:FileWriter(file,false)/FileWriter(file):对原有文件的覆盖
                        FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
* */
@Test
public void testFileWriter() {
    FileWriter fw= null;
    try {
        //1.提供file类的对象,指明写出到的文件
        File file = new File("hello1.txt");

        //2.FileWriter的对象,用于数据的写出
        fw = new FileWriter(file,false);

        //3.写出操作
        fw.write("can can need\n");
        fw.write("show show way");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        //4.流的关闭
        if(fw!=null) {
            try {
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


}

@Test
public void testFileReaderFileWriter(){
    FileReader fr = null;
    FileWriter fw = null;
    try {
        //1.创建File类的对象,指明读入和写出的文件
        //不能用字符流处理图片等字节流文件
        File srcfile = new File("hello.txt");
        File destfile = new File("hello2.txt");
        //2.创建输入输出流的对象
        fr = new FileReader(srcfile);
        fw = new FileWriter(destfile);

        //3.数据的读入写出
        char[] cbuf=new char[5];
        int len;//记录每次读入cbuf的个数
        while((len=fr.read(cbuf))!=-1){
            fw.write(cbuf,0,len);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        //4.流的关闭
        try {
            if(fw!=null) {
                fw.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            if(fr!=null) {
                fr.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

FileInputSteam和FileOutputStream

结论:

  • 对于文本文件(txt java c c++…),使用字符流处理
  • 对于非文本文件(jpg mp3 mp4 avi doc ppt…),使用字节流处理
/*
实现对图片的复制操作
* */
@Test
public void testFileInputOutputStream(){
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        //1.file类的实例化
        File srcFile = new File("编程背景.png");
        File destFile = new File("编程背景1.png");
        //2.流的实例化
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        //3.数据操作
        byte[] buffer=new byte[5];
        int len;
        while((len=fis.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        //4.流的关闭
        if(fos!=null) {
            try {
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if(fis!=null) {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}

缓冲流的使用

处理流之一缓冲流

1.缓冲流:BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter

2.作用:提高流的读取、写入速度

​ 提高写入速度的原因:内部提供了一个缓冲区。默认情况下是8kb

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4uH3tZZs-1665152817929)(C:\Users\zhangshuaibao\AppData\Roaming\Typora\typora-user-images\image-20221004173251579.png)]

3.处理流,就是“套接”在已有的流的基础上

 /*
    实现非文本文件的复制
    * */
    @Test
    public void BufferedStreamTest(){
        FileInputStream fis= null;
        FileOutputStream fos = null;
        BufferedInputStream bis= null;
        BufferedOutputStream bos = null;
        try {
            //1.file类实例化
            File srcFile = new File("编程背景.png");
            File destFile = new File("编程背景2.png");
            //2.流的实例化
            //2.1节点流
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            //2.2缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.数据操作
            byte[] buffer=new byte[10];
            int len;
            while((len=bis.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //4.流的关闭
            //要求:先关闭外层流,再关闭内层流,从下往上关。
            if(bos!=null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(bis!=null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            //说明:在关闭外层流的同时,内层流也会自动进行关闭
//            if(fos!=null) {
//                try {
//                    fos.close();
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//            if(fis!=null) {
//                try {
//                    fis.close();
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            }
        }

    }
    //实现文件复制的方法
    public void copyFileWithBufferd(String srcPtah,String destPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.file类实例化
            File srcFile = new File(srcPtah);
            File destFile = new File(destPath);
            //2.流的实例化
            //2.1节点流
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            //2.2缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.数据操作
            byte[] buffer = new byte[10];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
//                bos.flush();//刷新缓冲区
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //4.流的关闭
            //要求:先关闭外层流,再关闭内层流,从下往上关。
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    @Test
    public void testCopyWithBufferd(){
        long start = System.currentTimeMillis();
        String scrPath="编程背景.png";
        String destPath="编程背景3.png";
//        String scrPath="hello.txt";
//        String destPath="hello3.txt";
        copyFileWithBufferd(scrPath,destPath);
        long end = System.currentTimeMillis();
        System.out.println("time="+(end-start));
    }

转换流的使用

处理流二:转换流

1.转换流:属于字符流

​ InputStreamReader:将一个字节的输入流转换为字符的输入流

​ OutputStreamWriter:将一个字符的输出流转换为字节的输出流

2.提供字节流与字符流之间的转换

3.解码:字接、字节数组————>字符数组、字符串

​ 编码:字符数组、字符串————>字接、字节数组

文件编码的方式(比如GBK):决定了解析时使用的字符集(也只能是GBK)

@Test
    public void Test1() throws IOException {
        FileInputStream fis=new FileInputStream("hello.txt");
        java.io.InputStreamReader isr=new java.io.InputStreamReader(fis);//使用系统默认的字符集
        //参数2指明了字符集,具体使用哪个,取决于文件保存时使用的字符集
//        InputStreamReader isr=new InputStreamReader(fis,"UTF-8");//使用系统默认的字符集
        char[] cbuf=new char[5];
        int len;
        while((len=isr.read(cbuf))!=-1){
            String str = new String(cbuf,0,len);
            System.out.print(str);
        }
        isr.close();
        fis.close();
    }

    @Test
    public void Test() throws IOException{
        File file1=new File("hello.txt");
        File file2=new File("hello_.txt");

        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);
        InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
        OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");

        char[] cbuf=new char[5];
        int len;
        while((len=isr.read(cbuf))!=-1){
            osw.write(cbuf,0,len);
        }
        osw.close();
        isr.close();
    }

其它流的使用

1.标准的输入输出流

​ System.in:标准输入流,默认从键盘输入

​ System.out:标准输出流,默认从控制台输出

​ System类的setIN(InputStream in)/setOut(PrintStream out)方式重新制定输入和输出的流

2.打印流

​ PrintStream,PrintWriter

说明:

​ 提供了一些列重载的print()和println()方法,用于多种数据类型的输出

​ System.out返回的是PrintStream的实例

PrintSream ps=new PrintSream("文件地址")
System.setOut(ps);

3.数据流

​ DataInputStream和DataOutputStream

作用:用于读取或写出基本数据类型的变量或字符串

@Test
public void Test3() throws IOException{
    DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
    dos.writeUTF("刘建辰");
    dos.flush();
    dos.writeInt(23);
    dos.flush();
    dos.writeBoolean(true);
    dos.flush();

    dos.close();
}

@Test
public void Test4() throws IOException{
    //1.
    DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
    //2.
    String s = dis.readUTF();
    int i = dis.readInt();
    boolean b = dis.readBoolean();
    System.out.println(s+i+b);

    //3.
    dis.close();

}



public static void main(String[] args) {
    BufferedReader br= null;
    try {
        InputStreamReader isr = new InputStreamReader(System.in);
        br = new BufferedReader(isr);

        while(true){
            String data=br.readLine();
            if("e".equalsIgnoreCase(data)||"exit".equalsIgnoreCase(data)){
                System.out.println("程序结束");
                break;
            }
            String upperCase = data.toUpperCase();
            System.out.println(upperCase);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(br!=null){
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
//System.in--->转换流--->BufferedReader的readLine()
@Test
public void Test1(){
    BufferedReader br= null;
    try {
        InputStreamReader isr = new InputStreamReader(System.in);
        br = new BufferedReader(isr);

        while(true){
            String data=br.readLine();
            if("e".equalsIgnoreCase(data)||"exit".equalsIgnoreCase(data)){
                System.out.println("程序结束");
                break;
            }
            String upperCase = data.toUpperCase();
            System.out.println(upperCase);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(br!=null){
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

}

对象流的使用

1.对象流:

ObjectInputStream和ObjectOutputStream

2.作用:

ObjectInputStream:内存中的对象——>存储中的文件、通过网络传输出去

ObjectOutputStream:存储中的文件、通过网络接受过来——>内存中的对象

用于存储和读取基本数据类型数据或对象的处理流,它的强大之处就是可以吧java中的对象写入到数据源中,也可以还原

​ 补充:ObjectInputStream和ObjectOutputStream不能序列化static和transient修饰的成员变量

4.序列化机制:

​ 对象序列化机制允许把内存中的java对象转换成平台无关的二进制流,从而允许把这种二进制流持久的保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点

​ 当其他程序获取这种二进制流,就可以恢复成原来的Java对象

序列化过程:

/*
序列化:将内存中的Java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream实现
*/
@Test
public void Test1(){
    ObjectOutputStream oos = null;
    try {
        //1.
        oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
        //2.
        oos.writeObject(new String("我测尼玛"));
        oos.flush();
        oos.writeObject(new Person("顶真",22));
        oos.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(oos!=null){
            //3.
            try {
                oos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

反序列化:

/*
反序列化:将磁盘文件中的对象还原为内存中的一个Java对象
* */
@Test
public void Test2(){
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("object.dat"));
        Object o = ois.readObject();
        String str=(String) o;
        Person o1 = (Person) ois.readObject();

        System.out.println(str);
        System.out.println(o1);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } finally {
        if(ois!=null){
            try {
                ois.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

类需要满足,才能序列化:

​ 1.需要实现接口:serializable(标识接口)

​ 2.当前类提供一个全局常量:serialVersionUID

​ 3.除了当前Person类需要实现Serializable接口外,还必须保证其内部所有属性也必须是可序列化的(默认情况下,基本数据类型可序列化)

RandomAccessFile的使用

特点:

​ 1.RandomAccessFile直接继承了Java.lang.Object类,实现了DataInput和DataOutput接口

​ 2.RandomAccessFile既可以作为输入流,又可以作为输出流

​ 3.如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建文件。如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认从头覆盖)

​ 4.可以通过相关操作,实现RandomAccessFile对数据的插入效果(seek(int pos)方法)

代码:

​ 即是输入流也是输出流

@Test
public void Test1()  {
    RandomAccessFile raf1 = null;
    RandomAccessFile raf2 = null;
    try {
        //1
        raf1 = new RandomAccessFile(new File("编程背景.png"),"r");
        raf2 = new RandomAccessFile(new File("编程背景1.png"),"rw");
        //2
        byte[] buffer=new byte[1024];
        int len;
        while((len=raf1.read(buffer))!=-1){
            raf2.write(buffer,0,len);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        //3.
        if(raf1!=null){
            try {
                raf1.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if(raf2!=null){
            try {
                raf2.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

使用RandomAccessFile实现数据的插入效果

/*
使用RandomAccessFile实现数据的插入效果
 */
@Test
public void Test3() throws IOException{
    RandomAccessFile raf1 =new RandomAccessFile("hello.txt","rw");
    raf1.seek(3);//将指针调到角标为3的位置
    //保存指针3后边的所有数据到StringBuilder中
    StringBuilder builder=new StringBuilder((int)new File("hello.txt").length());
    byte[] buffer=new byte[20];
    int len;
    while((len=raf1.read(buffer))!=-1){
        builder.append(new String(buffer,0,len));
    }
    //调回指针,写入xyz
    raf1.seek(3);
    raf1.write("xyz".getBytes());
    //将StringBuilder的数据协会到文件中
    raf1.write(builder.toString().getBytes());
    raf1.close();

}

Path、Paths、Files的使用

1.NIO的使用说明

NIO是从Java1.4开始引入的一套新的IO API,可以代替原来的IO

NIO与原来的IO同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的(IO是面向流的)、基于通道的IO操作。

NIO.2随着jdk7发布,对NIO进行的扩展,增强了对文件处理和文件系统特性的支持

2.Path的使用–jdk7

说明:

​ 使用Path替换原有的File类

3.Files工具类——jdk7

​ 作用:操作文件或文件目录的工具类

​ 常用方法:略

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值