Java IO流与NIO技术综合应用详细实例代码

 更新时间:2024年12月09日 11:13:59   作者:爪哇学长  
这篇文章主要给大家介绍了关于Java IO流与NIO技术综合应用的相关资料,文中包括了字节流和字符流,以及它们的高级特性如缓冲区、序列化和反序列化,同时还介绍了NIO中的通道和缓冲区,以及选择器的使用,需要的朋友可以参考下

字节流

输入流(InputStream)

FileInputStream:从文件系统中读取原始字节

import java.io.FileInputStream;
import java.io.IOException;

public class ReadFileBytes {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("input.txt")) {
            int content;
            while ((content = fis.read()) != -1) {
                System.out.print((char) content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ByteArrayInputStream:允许程序从一个字节数组中读取数据

import java.io.ByteArrayInputStream;

public class ReadByteArray {
    public static void main(String[] args) {
        byte[] buffer = "Hello, World!".getBytes();
        try (ByteArrayInputStream bis = new ByteArrayInputStream(buffer)) {
            int data;
            while ((data = bis.read()) != -1) {
                System.out.print((char) data);
            }
        }
    }
}

BufferedInputStream:为其他输入流添加缓冲功能

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class BufferedRead {
    public static void main(String[] args) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"))) {
            int content;
            while ((content = bis.read()) != -1) {
                System.out.print((char) content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ObjectInputStream:用于反序列化对象

import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;

class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;

    Person(String name) {
        this.name = name;
    }
}

public class DeserializeObject {
    public static void main(String[] args) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
            Person person = (Person) ois.readObject();
            System.out.println(person.name);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

输出流(OutputStream)

FileOutputStream:向文件系统中的文件写入原始字节

import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileBytes {
    public static void main(String[] args) {
        String data = "Hello, World!";
        byte[] buffer = data.getBytes();

        try (FileOutputStream fos = new FileOutputStream("output.txt")) {
            fos.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ByteArrayOutputStream:将输出的数据写入到字节数组中

import java.io.ByteArrayOutputStream;

public class WriteByteArray {
    public static void main(String[] args) {
        String data = "Hello, World!";
        byte[] buffer = data.getBytes();
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            baos.write(buffer);
            byte[] output = baos.toByteArray();
            System.out.println(new String(output));
        }
    }
}

BufferedOutputStream:为其他输出流提供缓冲区

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedWrite {
    public static void main(String[] args) {
        String data = "Hello, World!\n";
        byte[] buffer = data.getBytes();

        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {
            bos.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ObjectOutputStream:用于序列化对象

import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;

class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;

    Person(String name) {
        this.name = name;
    }
}

public class SerializeObject {
    public static void main(String[] args) {
        Person person = new Person("Alice");

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
            oos.writeObject(person);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

字符流

输入流(Reader)

FileReader:简化了从文件读取字符的过程

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class ReadFileChars {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

CharArrayReader:从字符数组中读取字符

import java.io.CharArrayReader;

public class ReadCharArray {
    public static void main(String[] args) {
        char[] chars = "Hello, World!".toCharArray();
        try (CharArrayReader car = new CharArrayReader(chars)) {
            int c;
            while ((c = car.read()) != -1) {
                System.out.print((char) c);
            }
        }
    }
}

BufferedReader:为其他字符输入流添加缓冲区

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedCharRead {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

InputStreamReader:桥接器,将字节流转换为字符流

import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.IOException;

public class ByteToChar {
    public static void main(String[] args) {
        try (InputStreamReader isr = new InputStreamReader(new FileInputStream("input.txt"), "UTF-8")) {
            int c;
            while ((c = isr.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出流(Writer)

FileWriter:简化了将字符写入文件的过程

import java.io.FileWriter;
import java.io.IOException;

public class WriteFileChars {
    public static void main(String[] args) {
        String data = "Hello, World!\n";

        try (FileWriter writer = new FileWriter("output.txt", true)) { // 追加模式
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

CharArrayWriter:将字符写入字符数组

import java.io.CharArrayWriter;

public class WriteCharArray {
    public static void main(String[] args) {
        String data = "Hello, World!";
        try (CharArrayWriter caw = new CharArrayWriter()) {
            caw.write(data);
            char[] output = caw.toCharArray();
            System.out.println(new String(output));
        }
    }
}

BufferedWriter:为其他字符输出流添加缓冲区

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedCharWrite {
    public static void main(String[] args) {
        String data = "Hello, World!\n";

        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt", true))) {
            bw.write(data);
            bw.newLine(); // 写入换行符
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

OutputStreamWriter:桥接器,将字符流转换为字节流

import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;

public class CharToByte {
    public static void main(String[] args) {
        String data = "Hello, World!";
        try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8")) {
            osw.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

高级特性

Piped Streams:管道流使得一个线程可以通过管道将数据发送给另一个线程

import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.IOException;

class Producer implements Runnable {
    private PipedOutputStream pos;

    Producer(PipedInputStream pis) throws IOException {
        pos = new PipedOutputStream(pis);
    }

    @Override
    public void run() {
        try {
            String data = "Hello, Pipe!";
            pos.write(data.getBytes());
            pos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Consumer implements Runnable {
    private PipedInputStream pis;

    Consumer(PipedOutputStream pos) throws IOException {
        pis = new PipedInputStream(pos);
    }

    @Override
    public void run() {
        try {
            int data;
            while ((data = pis.read()) != -1) {
                System.out.print((char) data);
            }
            pis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class PipeStreams {
    public static void main(String[] args) throws IOException {
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream(pis);

        Thread producerThread = new Thread(new Producer(pos));
        Thread consumerThread = new Thread(new Consumer(pis));

        producerThread.start();
        consumerThread.start();
    }
}

PrintStream:格式化输出流,通常用于标准输出(控制台)

import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class UsePrintStream {
    public static void main(String[] args) {
        try (PrintStream ps = new PrintStream(new FileOutputStream("output.txt"))) {
            ps.println("Hello, PrintStream!");
            ps.printf("This is a formatted string: %d%%\n", 100);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Scanner:用于解析基础数据类型和字符串

import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class UseScanner {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(new File("input.txt"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Formatter:用于格式化输出

import java.io.PrintWriter;
import java.io.StringWriter;

public class UseFormatter {
    public static void main(String[] args) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.format("Hello, %s!\n", "Formatter");
        pw.format("Formatted integer: %d\n", 42);
        System.out.println(sw.toString());
    }
}

NIO (New IO)

Channels 和 Buffers

使用FileChannel和ByteBuffer读写文件

import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.io.IOException;

public class NIOExample {
    public static void main(String[] args) {
        Path path = Paths.get("output.txt");
        String data = "Hello NIO!";

        // Writing to file using FileChannel and ByteBuffer
        try (FileChannel channel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put(data.getBytes(StandardCharsets.UTF_8));
            buffer.flip(); // Switch to read mode
            channel.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Reading from file using FileChannel and ByteBuffer
        try (FileChannel channel = FileChannel.open(path)) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int bytesRead = channel.read(buffer);
            buffer.flip(); // Switch to read mode
            byte[] bytes = new byte[bytesRead];
            buffer.get(bytes);
            System.out.println(new String(bytes, StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Selectors

选择器的使用稍微复杂一些,它主要用于网络编程中,以实现非阻塞I/O。这里提供一个简单的例子来展示如何创建和使用选择器监控多个SocketChannel

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.spi.SelectorProvider;

public class SelectorExample {
    public static void main(String[] args) throws IOException {
        // Open a selector
        Selector selector = SelectorProvider.provider().openSelector();

        // Open a server socket channel and bind it to port 8080
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.socket().bind(new InetSocketAddress(8080));
        serverChannel.configureBlocking(false);

        // Register the server channel with the selector for accepting connections
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        // Loop indefinitely, waiting for events on the channels registered with the selector
        while (true) {
            // Wait for at least one event
            selector.select();

            // Get the set of keys with pending events
            for (SelectionKey key : selector.selectedKeys()) {
                // Remove the current key from the set so it won't be processed again
                selector.selectedKeys().remove(key);

                if (!key.isValid()) {
                    continue;
                }

                // Check what event is ready and handle it
                if (key.isAcceptable()) {
                    // Accept the new connection
                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    // Register the new SocketChannel with the selector for reading
                    sc.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    // Read the data from the client
                    SocketChannel sc = (SocketChannel) key.channel();
                    // ... handle reading ...
                }
            }
        }
    }
}

总结 

到此这篇关于Java IO流与NIO技术综合应用的文章就介绍到这了,更多相关Java IO流与NIO技术应用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot接口如何对参数进行校验

    SpringBoot接口如何对参数进行校验

    这篇文章主要介绍了SpringBoot接口如何对参数进行校验,在以SpringBoot开发Restful接口时, 对于接口的查询参数后台也是要进行校验的,同时还需要给出校验的返回信息放到上文我们统一封装的结构中
    2022-07-07
  • SpringBoot手动开启事务:DataSourceTransactionManager问题

    SpringBoot手动开启事务:DataSourceTransactionManager问题

    这篇文章主要介绍了SpringBoot手动开启事务:DataSourceTransactionManager问题,具有很好的价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • Java编程中应用的GUI设计基础

    Java编程中应用的GUI设计基础

    这篇文章主要介绍了Java编程中应用的GUI设计基础,为一些Java开发CS类型应用的基础概念知识,需要的朋友可以参考下
    2015-10-10
  • idea每次新打开的项目窗口maven都要重新设置问题

    idea每次新打开的项目窗口maven都要重新设置问题

    这篇文章主要介绍了idea每次新打开的项目窗口maven都要重新设置问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • maven一键删除仓库无用文件的实现

    maven一键删除仓库无用文件的实现

    大家都知道我们在使用Maven的时候,会下载一堆无用非jar文件,本文主要介绍了maven一键删除仓库无用文件的实现,具有一定的参考价值,感兴趣的可以了解一下
    2023-11-11
  • MyEclipse整合ssh三大框架环境搭载用户注册源码下载

    MyEclipse整合ssh三大框架环境搭载用户注册源码下载

    这篇文章主要为大家详细介绍了如何使用MyEclipse整合ssh三大框架进行环境搭载,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • cmd中javac命令无法运行(java指令能运行)解决步骤

    cmd中javac命令无法运行(java指令能运行)解决步骤

    这篇文章主要介绍了在安装JDK后,执行javac命令没有返回值的问题,可能是由于命令提示符窗口缓存问题、系统路径优先级问题、文件权限问题或命令行输入问题,文中通过代码将解决的步骤介绍的非常详细,需要的朋友可以参考下
    2025-02-02
  • JAVA设计模式之调停者模式详解

    JAVA设计模式之调停者模式详解

    这篇文章主要介绍了JAVA设计模式之调停者模式详解,调停者模式是对象的行为模式,调停者模式包装了一系列对象相互作用的方式,使得这些对象不必相互明显引用,从而使它们可以较松散地耦合,需要的朋友可以参考下
    2015-04-04
  • Java多线程连续打印abc实现方法详解

    Java多线程连续打印abc实现方法详解

    这篇文章主要介绍了Java多线程连续打印abc实现方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • SpringCloud微服务基础简介

    SpringCloud微服务基础简介

    今天带大家学习一下SpringCloud微服务的相关知识,文中有非常详细的图文示例及介绍,对正在学习SpringCloud微服务的小伙伴们很有帮助哦,需要的朋友可以参考下
    2021-05-05

最新评论