Java常用数据流全面大梳理

 更新时间:2021年10月06日 13:22:42   作者:叶绿体不忘呼吸  
计算机程序中,获取数据的方式有多种,比如:程序中直接给出、键盘输入、从数据文件中读取、从数据库中读取、通过网络读取等。为了更有效地进行数据的输入/输出操作,Java将各种数据源的数据,抽象为“数据流”,及stream

缓冲流

为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。

在这里插入图片描述

缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:
BufferedInputStreamBufferedOutputStream
BufferedReaderBufferedWriter

当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区。当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。

向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,
BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法
flush()可以强制将缓冲区的内容全部写入输出流。

关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也
会相应关闭内层节点流。

flush()方法的使用:手动将buffer中内容写入文件。使用带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,相当于自动调用了flush()方法,关闭后不能再写出。

在这里插入图片描述

以字节流BufferedInputStreamBufferedOutputStream示例具体操作:

import java.io.*;

/**
 * @Author: Yeman
 * @Date: 2021-09-25-22:36
 * @Description:
 */
public class BufferedTest {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        BufferedInputStream bfi = null;
        BufferedOutputStream bfo = null;
        try {
            //1、实例化File对象,指定文件
            File inFile = new File("IO\\input.jpg");
            File outFile = new File("IO\\output.jpg");
            //2、创建节点流(文件流)对象
            fis = new FileInputStream(inFile);
            fos = new FileOutputStream(outFile);
            //3、创建处理节点流的缓冲流对象
            bfi = new BufferedInputStream(fis);
            bfo = new BufferedOutputStream(fos);
            //4、通过缓冲流进行读写操作
            byte[] bytes = new byte[1024];
            int length = bfi.read(bytes);
            while (length != -1){
                bfo.write(bytes,0,length);
                length = bfi.read(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5、关闭外层流,内存流便自动关闭
            try {
                if (bfi != null) bfi.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bfo != null) bfo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

转换流

转换流提供了在字节流和字符流之间的转换。

InputStreamReader:将InputStream转换为Reader(字节转为字符输入)
OutputStreamWriter:将Writer转换为OutputStream(字节转为字符输出)

字节流中的数据都是字符时,转成字符流操作更高效。使用转换流来处理文件乱码问题,实现编码和解码的功能。

在这里插入图片描述

InputStreamReader:
实现将字节的输入流按指定字符集转换为字符的输入流。需要和InputStream“套接”。
构造器:
public InputStreamReader(InputStream in)
public InputSreamReader(InputStream in,String charsetName)

在这里插入图片描述

OutputStreamWriter:
实现将字符的输出流按指定字符集转换为字节的输出流。需要和OutputStream“套接”。
构造器:
public OutputStreamWriter(OutputStream out)
public OutputSreamWriter(OutputStream out,String charsetName)

import java.io.*;

/**
 * @Author: Yeman
 * @Date: 2021-09-26-20:13
 * @Description:
 */
public class Test {
    public static void main(String[] args) {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            //1、指明输入输出文件
            File inFile = new File("IO\\hi.txt");
            File outFile = new File("IO\\hello.txt");
            //2、提供字节节点流
            FileInputStream fis = new FileInputStream(inFile);
            FileOutputStream fos = new FileOutputStream(outFile);
            //3、提供转换流
            isr = new InputStreamReader(fis,"gbk");
            osw = new OutputStreamWriter(fos,"utf-8");
            //4、读写操作
            char[] chars = new char[10];
            int len = isr.read(chars);
            while (len != -1){
                osw.write(chars,0,len);
                len = isr.read(chars);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5、关闭外层流
            try {
                if (osw != null) osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (isr != null) isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

标准输入输出流

System.inSystem.out分别代表了系统标准的输入和输出设备
默认输入设备是:键盘,输出设备是:显示器(控制台)

System.in的类型是InputStream
System.out的类型是PrintStream,其是OutputStream的子类

重定向:通过System类的setIn()setOut()方法对默认设备进行改变:
public static void setIn(InputStream in)
public static void setOut(PrintStream out)

在这里插入图片描述

import java.io.*;

/**
 * @Author: Yeman
 * @Date: 2021-09-26-20:13
 * @Description:
 */
public class Test {
    public static void main(String[] args) {
        BufferedReader bis = null;
        try {
            //1、提供转换流(System.in是字节流,将其转换为字符流)
            System.out.println("请输入信息(退出输入e或exit):");
            InputStreamReader isr = new InputStreamReader(System.in);
            //2、提供缓冲流将输入的一行读取
            bis = new BufferedReader(isr);
            //3、读操作
            String s = null;
            while ((s = bis.readLine()) != null){
                if ("e".equalsIgnoreCase(s) || "exit".equalsIgnoreCase(s)){
                    System.out.println("程序结束,退出程序!");
                    break;
                }
                System.out.println("==" + s.toUpperCase());
                System.out.println("继续输入(退出输入e或exit):");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4、关闭外层流
            try {
                if (bis != null) bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

打印流

实现将基本数据类型的数据格式转化为字符串输出。

打印流:PrintStreamPrintWriter
提供了一系列重载的print()println()方法,用于多种数据类型的输出:
PrintStream和PrintWriter的输出不会抛出IOException异常,
PrintStream和PrintWriter有自动flush功能,
PrintStream打印的所有字符都使用平台的默认字符编码转换为字节
在需要写入字符而不是写入字节的情况下,应该使用PrintWriter类。

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

常与System.out搭配使用,可以不在控制台输出,而是输出到指定位置:

import java.io.*;

/**
 * @Author: Yeman
 * @Date: 2021-09-26-20:13
 * @Description:
 */
public class Test {
    public static void main(String[] args) {
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("IO\\text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
            ps = new PrintStream(fos, true);
            if (ps != null) {// 把标准输出流(控制台输出)改成文件
                System.setOut(ps);
            }
            for (int i = 0; i <= 255; i++) { // 输出ASCII字符
                System.out.print((char) i);
                if (i % 50 == 0) { // 每50个数据一行
                    System.out.println(); // 换行
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
        }

    }
}

数据流

为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。

数据流有两个类:(用于读取和写出基本数据类型、String类的数据)
DataInputStreamDataOutputStream
分别“套接”在 InputStream 和 OutputStream 子类的流上。

在这里插入图片描述

import java.io.*;

/**
 * @Author: Yeman
 * @Date: 2021-09-26-20:13
 * @Description:
 */
public class Test {
    public static void main(String[] args) {

        //写
        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(new FileOutputStream("IO\\test.txt"));
            dos.writeUTF("叶绿体");
            dos.writeInt(22);
            dos.writeBoolean(true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dos != null) dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //读
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(new FileInputStream("IO\\test.txt"));
            //注意读的顺序要和写的顺序一样
            String name = dis.readUTF();
            int age = dis.readInt();
            boolean isMan = dis.readBoolean();
            System.out.println(name + age + isMan);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dis != null) dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

对象流

ObjectInputStreamOjbectOutputSteam

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

序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
反序列化:用ObjectInputStream类读取基本类型数据或对象的机制

ObjectOutputStreamObjectInputStream不能序列化statictransient修饰的成员变量。

实现Serializable或者Externalizable两个接口之一的类的对象才可序列化,关于对象序列化详见:

可序列化对象:

import java.io.Serializable;

/**
 * @Author: Yeman
 * @Date: 2021-09-27-8:27
 * @Description:
 */

class pet implements Serializable {
    public static final long serialVersionUID = 999794470754667999L;
    private String name;

    public pet(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "pet{" +
                "name='" + name + '\'' +
                '}';
    }
}

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

    public Person(String name, int age, pet pet) {
        this.name = name;
        this.age = age;
        this.pet = pet;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", pet=" + pet +
                '}';
    }
}

序列化(ObjectOutputStream):

import java.io.*;

/**
 * @Author: Yeman
 * @Date: 2021-09-26-20:13
 * @Description:
 */
public class Test {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("IO\\test.txt"));
            oos.writeUTF(new String("你好世界!"));
            oos.flush();
            oos.writeObject(new Person("Lily",20,new pet("Xinxin")));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null) oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

反序列化(ObjectInputStream):

import java.io.*;

/**
 * @Author: Yeman
 * @Date: 2021-09-26-20:13
 * @Description:
 */
public class Test {
    public static void main(String[] args) {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("IO\\test.txt"));
            String s = ois.readUTF();
            Person o = (Person) ois.readObject();
            System.out.println(o.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

随机存取文件流

RandomAccessFile声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInputDataOutput这两个接口,也就意味着这个类既可以读也可以写。

RandomAccessFile类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来读写文件:①支持只访问文件的部分内容②可以向已存在的文件后追加内容③若文件不存在,则创建④若文件存在,则从指针位置开始覆盖内容,而不是覆盖文件。

RandomAccessFile对象包含一个记录指针,用以标示当前读写处的位置,RandomAccessFile类对象可以自由移动记录指针:
long getFilePointer():获取文件记录指针的当前位置
void seek(long pos):将文件记录指针定位到 pos 位置

构造器:

public RandomAccessFile(File file, String mode)
public RandomAccessFile(String name, String mode)
创建 RandomAccessFile 类实例需要指定一个 mode 参数,该参数指定 RandomAccessFile 的访问模式:

在这里插入图片描述

如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。 如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建。

import java.io.*;

/**
 * @Author: Yeman
 * @Date: 2021-09-26-20:13
 * @Description:
 */
public class Test {
    public static void main(String[] args) {
        RandomAccessFile r1 = null;
        RandomAccessFile rw = null;
        try {
            r1 = new RandomAccessFile("IO\\input.jpg", "r");
            rw = new RandomAccessFile("IO\\output.jpg", "rw");

            byte[] bytes = new byte[1024];
            int len = r1.read(bytes);
            while (len != -1){
                rw.write(bytes,0,len);
                len = r1.read(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rw != null) rw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (r1 != null) r1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

Java NIO

Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新的IO API,可以替代标准的Java IO API。NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的(IO是面向流的)、基于通道的IO操作,NIO将以更加高效的方式进行文件的读写操作。

Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO。

在这里插入图片描述

随着 JDK 7 的发布,Java对NIO进行了极大的扩展,增强了对文件处理和文件系统特性的支持,以至于我们称他们为 NIO.2。因为 NIO 提供的一些功能,NIO已经成为文件处理中越来越重要的部分。

早期的Java只提供了一个File类来访问文件系统,但File类的功能比较有限,所提供的方法性能也不高。而且,大多数方法在出错时仅返回失败,并不会提供异常信息。
NIO. 2为了弥补这种不足,引入了Path接口,代表一个平台无关的平台路径,描述了目录结构中文件的位置。Path可以看成是File类的升级版本,实际引用的资源也可以不存在。

在以前IO操作都是这样写的:

import java.io.File;
File file = new File("index.html");

但在Java7 中,可以这样写:

import java.nio.file.Path; 
import java.nio.file.Paths; 
Path path = Paths.get("index.html");

同时,NIO.2在java.nio.file包下还提供了Files、Paths工具类,Files包含了大量静态的工具方法来操作文件;Paths则包含了两个返回Path的静态工厂方法。

Paths 类提供的静态 get() 方法用来获取 Path 对象:
static Path get(String first, String … more) : 用于将多个字符串串连成路径
static Path get(URI uri): 返回指定uri对应的Path路径

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

到此这篇关于Java常用数据流全面大梳理的文章就介绍到这了,更多相关Java 数据流内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java中concat()方法的使用说明

    java中concat()方法的使用说明

    这篇文章主要介绍了java中concat()方法的使用说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • java设计模式--策略模式详解

    java设计模式--策略模式详解

    这篇文章主要介绍了Java经典设计模式之策略模式,简单说明了策略模式的概念、原理并结合实例形式分析了java策略模式的具有用法与相关注意事项,需要的朋友可以参考下
    2021-07-07
  • Java过滤器与监听器间区别与联系

    Java过滤器与监听器间区别与联系

    监听器是一个接口内容由我们实现,会在特定时间被调用,监听器用于监听web应用中三大域对象(request,session,application),信息的创建,销毁,增加,修改,删除等动作的发生,然后做出相应的响应处理
    2023-01-01
  • java中的forkjoin框架的使用

    java中的forkjoin框架的使用

    这篇文章主要介绍了java中的fork join框架的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-03-03
  • Java数据结构之选择排序算法的实现与优化

    Java数据结构之选择排序算法的实现与优化

    选择排序:(Selection sort)是一种简单直观的排序算法,也是一种不稳定的排序方法。本文主要为大家介绍一下选择排序的实现与优化,希望对大家有所帮助
    2023-01-01
  • Java Swagger技术使用指南

    Java Swagger技术使用指南

    Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步
    2021-09-09
  • 全面解析Spring Security 过滤器链的机制和特性

    全面解析Spring Security 过滤器链的机制和特性

    这篇文章主要介绍了Spring Security 过滤器链的机制和特性,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • 老生常谈比较排序之归并排序(递归)

    老生常谈比较排序之归并排序(递归)

    下面小编就为大家带来一篇老生常谈比较排序之归并排序(递归)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • JAVA8发送带有Body的HTTP GET请求

    JAVA8发送带有Body的HTTP GET请求

    本文主要介绍了JAVA8发送带有Body的HTTP GET请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • Java数组动态增加容量过程解析

    Java数组动态增加容量过程解析

    这篇文章主要介绍了Java数组动态增加容量过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09

最新评论