Java基础之IO&NIO操作文件流

简介: Java基础之IO&NIO操作文件流

一、简介

1.1 IO(BIO)—阻塞式IO

起源于JDK1.0

网络异常,图片无法展示
|


  • java.io 包几乎包含了所有操作输入、输出需要的类。
  • 所有这些流类代表了输入源和输出目标。
  • java.io 包中的流支持很多种格式,比如:基本类型、对象、本地化字符集等等。
    一个流可以理解为一个数据的序列。
  • 输入流表示从一个源读取数据,输出流表示向一个目标写数据。
  • Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。

1.2 NIO—非阻塞式IO

起源于JDK1.4

网络异常,图片无法展示
|


  • Java NIO可以让你非阻塞的使用IO,例如:当线程从通道读取数据到缓冲区时,线程还是可以进行其他事情。当数据被写入到缓冲区时,线程可以继续处理它。从缓冲区写入通道也类似。

1.3 BIO和NIO对比

  • 标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(Buffer)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。

二、使用

2.1 BIO使用

2.1.1 读取文件内容到控制台

/**
     * IO读取文件到控制台
     */
    public static void readFile() {
        File file = new File("D:\\desktop\\io.txt");
        try {
            FileReader fr = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fr);
            String str = bufferedReader.readLine();
            while (str != null) {
                System.out.println(str);
                str = bufferedReader.readLine();//将reader置为空
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
复制代码


2.1.2 写入文本内容到文件中

/**
     * IO写入(生成)文件
     */
    public static void writeFile() {
        File file = new File("D:\\desktop\\io2.txt");
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            String str = "Hello Write File";
            outputStream.write(str.getBytes());
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
复制代码


2.1.3 复制文件

/**
     * IO复制文件
     */
    public static void copyFile() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream("D:\\desktop\\Linux软件安装包.zip"); //文件大小387M
            outputStream = new FileOutputStream("D:\\desktop\\Linux软件安装包_cp.zip");
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
复制代码


2.2 NIO使用

2.2.1 NIO方式读取文件内容

/**
     * NIO读取文件
     */
    public static void read() {
        RandomAccessFile access = null;
        try {
            access = new RandomAccessFile(new File("D:\\desktop\\io.txt"), "r");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileChannel channel = access.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);
        Charset charset = Charset.forName("utf-8");
        CharsetDecoder decoder = charset.newDecoder();
        int length = 0;
        try {
            length = channel.read(byteBuffer);
            while (length != -1) {
                byteBuffer.flip();
                decoder.decode(byteBuffer, charBuffer, true);
                charBuffer.flip();
                System.out.println(charBuffer.toString());
                if (byteBuffer != null) byteBuffer.clear();
                if (charBuffer != null) charBuffer.clear();
                length = channel.read(byteBuffer); // 再次读取文本内容
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (channel != null) channel.close();
                if (access != null) access.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
复制代码


2.2.2 NIO方式写入文件

/**
     * NIO写文件
     *
     * @param context
     * @throws IOException
     */
    public static void write(String context) {
        FileOutputStream outputStream = null;
        FileChannel channel = null;
        try {
            outputStream = new FileOutputStream(new File("D:\\desktop\\nio.txt"), true);//允许文件内容追加而不是覆盖
            channel = outputStream.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put(context.getBytes("utf-8"));
            byteBuffer.flip();//读取模式转换为写入模式
            channel.write(byteBuffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (channel != null) channel.close();
                if (outputStream != null) outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
复制代码


2.2.3 NIO方式复制文件

/**
     * NIO复制文件
     *
     * @param source
     * @param target
     */
    public static void nioCopy(String source, String target) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        FileInputStream inputStream = null;
        FileChannel inChannel = null;
        FileOutputStream outputStream = null;
        FileChannel outChannel = null;
        try {
            inputStream = new FileInputStream(source);
            inChannel = inputStream.getChannel();
            outputStream = new FileOutputStream(target);
            outChannel = outputStream.getChannel();
            int length = 0;
            length = inChannel.read(byteBuffer);
            while (length != -1) {
                byteBuffer.flip();//读取模式转换写入模式
                outChannel.write(byteBuffer);
                byteBuffer.clear(); //清空缓存,等待下次写入
                length = inChannel.read(byteBuffer); // 再次读取文本内容
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
                outChannel.close();
                inputStream.close();
                inChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


相关文章
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
512 1
|
Java 测试技术 API
Java IO流(二):文件操作与NIO入门
本文详解Java NIO与传统IO的区别与优势,涵盖Path、Files类、Channel、Buffer、Selector等核心概念,深入讲解文件操作、目录遍历、NIO实战及性能优化技巧,适合处理大文件与高并发场景,助力高效IO编程与面试准备。
|
SQL Java 数据库连接
Java IO流(一):字节流与字符流基础
本文全面解析Java IO流,涵盖字节流、字符流及其使用场景,帮助开发者理解IO流分类与用途,掌握文件读写、编码转换、异常处理等核心技术,通过实战案例提升IO编程能力。
|
存储 Java Linux
操作系统层面视角下 Java IO 的演进路径及核心技术变革解析
本文从操作系统层面深入解析Java IO的演进历程,涵盖BIO、NIO、多路复用器及Netty等核心技术。分析各阶段IO模型的原理、优缺点及系统调用机制,探讨Java如何通过底层优化提升并发性能与数据处理效率,全面呈现IO技术的变革路径与发展趋势。
354 3
|
监控 Java API
现代 Java IO 高性能实践从原理到落地的高效实现路径与实战指南
本文深入解析现代Java高性能IO实践,涵盖异步非阻塞IO、操作系统优化、大文件处理、响应式网络编程与数据库访问,结合Netty、Reactor等技术落地高并发应用,助力构建高效可扩展的IO系统。
556 0
|
存储 网络协议 安全
Java网络编程,多线程,IO流综合小项目一一ChatBoxes
**项目介绍**:本项目实现了一个基于TCP协议的C/S架构控制台聊天室,支持局域网内多客户端同时聊天。用户需注册并登录,用户名唯一,密码格式为字母开头加纯数字。登录后可实时聊天,服务端负责验证用户信息并转发消息。 **项目亮点**: - **C/S架构**:客户端与服务端通过TCP连接通信。 - **多线程**:采用多线程处理多个客户端的并发请求,确保实时交互。 - **IO流**:使用BufferedReader和BufferedWriter进行数据传输,确保高效稳定的通信。 - **线程安全**:通过同步代码块和锁机制保证共享数据的安全性。
843 23
|
缓存 网络协议 Java
JAVA网络IO之NIO/BIO
本文介绍了Java网络编程的基础与历史演进,重点阐述了IO和Socket的概念。Java的IO分为设备和接口两部分,通过流、字节、字符等方式实现与外部的交互。
710 0
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
781 1
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
693 1
|
数据采集 存储 弹性计算
高并发Java爬虫的瓶颈分析与动态线程优化方案
高并发Java爬虫的瓶颈分析与动态线程优化方案