Java教程

JAVA IO流详解

本文主要是介绍JAVA IO流详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

File

File是java.io包下的类,代表与平台无关的文件和目录

  • File能创建,删除,重命名文件和目录,也能检测,访问文件和目录本身
  • File不能访问文件中的内容,如果要访问内容,则需要使用输入,输出流

在这里插入图片描述

过滤文件

  1. File类的listFiles()方法可以接受一个参数,用于在列举文件时对其进行过滤;
  2. File类会依次将文件传给过滤器,当过滤器返回true时,File类才会列举该文件;

在这里插入图片描述
在这里插入图片描述

 public static void main(String[] args) {
        File dir = new File("D:/DXL/DXL5/A");

        File[] files=dir.listFiles();

        files=dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                System.out.println(pathname+"     sdad");
                return true;
            }
        });
        System.out.println("========================================================================================================");
        files=dir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                System.out.println(dir + "   " + name);
             if (name.endsWith("f")){
                 return false;
             }
             return true;
            }
        });

        System.out.println(Arrays.toString(files));

    }

在这里插入图片描述

遍历文件

public static void main(String[] args) {
      printFile("C:\\eSupport",0);
    }


    public  static void printFile(String filePath,int depth){

        File file = new File(filePath);

        if (!file.exists()){
            throw new IllegalArgumentException("文件不存在");
        }

//      打印空格
        for (int i = 0; i < depth; i++) {
            System.out.print(" ");
            
        }

//        打印名字
        if (file.isFile()){
            System.out.print(" - ");
        }
        System.out.println(file.getName());

//        目录递归  isDirectory判断是否是目录
        if (file.isDirectory()){
            File[] files = file.listFiles();
            for (File f:files){
                printFile(f.getPath(),depth+1 );
            }
        }

    }

IO流简介

  1. IO(Input Output)用于实现对数据的输入与输出操作;
  2. Java把不同的输入/输出源(键盘、文件、网络等)抽象表述为流(Stream);
  3. 流是从起源到接收的有序数据,程序采用同一方式可以访问不同的输入/输出源在这里插入图片描述

流的分类

  • 输入流和输出流(方向)
  • 输入流只能读取数据,不能写入数据;
  • 输出流只能写入数据,不能读取数据;
    字节流和字符流(数据)
  • 字节流操作的数据单元是 8位的字节;
  • 字符流操作的数据单元是16位的字符;
    节点流和处理流(功能)
  • 节点流可以直接从/向一个特定的IO设备(磁盘、网络等)读/写数据,也称为低级流;
  • 处理流是对节点流的连接或封装,用于简化数据读/写功能或提高效率,也称为高级流

在这里插入图片描述

流的 模型

在这里插入图片描述

抽象基类

输入流

在这里插入图片描述
在这里插入图片描述

输出流

在这里插入图片描述
在这里插入图片描述

注意事项

  1. 上述四个类都是抽象类,不能直接实例化;
  2. 上述四个类都定义了close()方法,你需要在使用流之后调用此方法将其关闭;
  3. 无论是否发生异常,使用流后都要尝试关闭它,所以通常在finally中关闭流;
  4. 上述四个类都实现了Closeable接口,因此可以在try()中创建流,以便于自动关闭。

文件流

在这里插入图片描述

 public static void main(String[] args) {


//      copyFile("D:\\javaidea\\IntelliJ IDEA 2021.1.3\\icons.db","D:\\javaidea\\");
         copyTxtFile("D:\\DXL\\dfsf.txt","D:\\DXL\\dfsf副本.txt");
    }

    public static void copyFile(String srcFilePath,String destFile){

        try (
                FileInputStream fis=new FileInputStream(srcFilePath);
              FileOutputStream fos=  new FileOutputStream(destFile)
        ){
            byte[] bytes = new byte[128];
            int len=0;//实际获取的字节数
            while ((len=fis.read(bytes, 0,bytes.length))>0){

                fos.write(bytes,0,len);

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

//    拷贝文本文件
    public static void copyTxtFile(String srcFilePath,String destFile){

        try (

            FileReader  fr =new FileReader(srcFilePath);
            FileWriter  fw= new FileWriter(destFile);
                ){
            char[] chars=new char[128];
            int len=0;//获取实际读取的字符数
            while ((len=fr.read(chars,0, chars.length))>0){
                System.out.println(String.valueOf(chars, 0, len));
                fw.write(chars,0,len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

缓冲流

在这里插入图片描述

  1. 这四个类都是处理流,需要关联对应的节点流,即实例化时需传入节点流实例;
  2. 缓冲流内部维护了一个缓冲区,通过与缓冲区的交互,减少与设备的交互次数;
  3. 使用缓冲输入流时,它每次会读取一批数据将缓冲区填满,每次调用读取方法并不是直接
    从设备取值,而是从缓冲区取值,当缓冲区为空时,它会再一次读取数据,将缓冲区填满;
  4. 使用缓冲输出流时,每次调用写入方法并不是直接写入到设备,而是写入缓冲区,当缓冲
    区填满时它会自动刷入设备,也可以调用flush()方法触发刷入(关闭流时会自动调它)。
 public static void main(String[] args) {

        long l = System.currentTimeMillis();
        copyFile("D:\\下载集中地\\BaiduNetdisk_7.4.3.3.exe","D:\\下载集中地\\BaiduNetdisk副本_7.4.3.3.exe");

        long end = System.currentTimeMillis();
        System.out.println("用时:;" + (end - l));

    }

    public static void copyFile(String scrFile,String desFile){

        try (
               
                BufferedInputStream bis= new BufferedInputStream(new FileInputStream(scrFile));
                 BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(desFile));
//                FileInputStream  bis  = new FileInputStream(scrFile);
//                FileOutputStream bos  = new FileOutputStream(desFile);

                ){
            byte[] bytes = new byte[128];
            int len=0;
            while ((len=bis.read(bytes,0,bytes.length))>0){
                bos.write(bytes,0,len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

在这里插入图片描述
在这里插入图片描述

第一个是缓冲流复制时间 第二个是文件流复制时间

转换流

在这里插入图片描述

  1. 这2个类都是处理流,需要关联对应的节点流,即实例化时需传入节点流实例;
  2. Scanner所提供的输入方法,其底层是采用InputStreamReader类实现的;
  3. PrintStream所提供的输出方法,其底层是采用OutputStreamWriter实现的。
 public static void main(String[] args) {

        try (
                InputStreamReader r=new InputStreamReader(System.in);
                BufferedReader  br=new BufferedReader(r);
                ){
            String line=null;
            while ((line=br.readLine())!=null){
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

打印流

在这里插入图片描述

  1. 这2个类都是处理流,需要关联对应的节点流,即实例化时需传入节点流实例;
  2. System.out就是PrintStream类型;
  3. PrintStream、PrintWriter的功能和方法基本相同,后者的设计更合理
    public static void main(String[] args) {
      testPrintStream();
    }


    public static void testPrintStream() {

    try (
            FileOutputStream fos=new FileOutputStream("D:\\DXL\\dfsf.txt");
            PrintStream ps=new PrintStream(fos);

            ){
        ps.println("我爱");
        ps.print("java");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    }

在这里插入图片描述

这篇关于JAVA IO流详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!