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

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

一、简介

1.1 IO(BIO)---阻塞式IO

起源于JDK1.0
image.png

  • java.io 包几乎包含了所有操作输入、输出需要的类。
  • 所有这些流类代表了输入源和输出目标。
  • java.io 包中的流支持很多种格式,比如:基本类型、对象、本地化字符集等等。

一个流可以理解为一个数据的序列。

  • 输入流表示从一个源读取数据,输出流表示向一个目标写数据。
  • Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。

1.2 NIO---非阻塞式IO

起源于JDK1.4
image.png

  • 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();
            }
        }
    }
相关文章
|
16天前
|
Java Unix Windows
|
1天前
|
Java 开发者
Java一分钟之-Java IO流:文件读写基础
【5月更文挑战第10天】本文介绍了Java IO流在文件读写中的应用,包括`FileInputStream`和`FileOutputStream`用于字节流操作,`BufferedReader`和`PrintWriter`用于字符流。通过代码示例展示了如何读取和写入文件,强调了常见问题如未关闭流、文件路径、编码、权限和异常处理,并提供了追加写入与读取的示例。理解这些基础知识和注意事项能帮助开发者编写更可靠的程序。
8 0
|
6天前
|
存储 缓存 Java
Java IO 流详解
Java IO 流详解
15 1
|
10天前
|
存储 Java
Java的`java.io`包包含多种输入输出类
Java的`java.io`包包含多种输入输出类。此示例展示如何使用`FileInputStream`从`input.txt`读取数据。首先创建`FileInputStream`对象,接着分配一个`byte`数组存储流中的数据。通过`read()`方法读取数据,然后将字节数组转换为字符串打印。最后关闭输入流释放资源。`InputStream`是抽象类,此处使用其子类`FileInputStream`。其他子类如`ByteArrayInputStream`、`ObjectInputStream`和`BufferedInputStream`各有特定用途。
19 1
|
11天前
|
存储 Java
java IO接口(Input)用法
【5月更文挑战第1天】Java的`java.io`包包含多种输入输出类。此示例展示了如何使用`FileInputStream`从`input.txt`读取数据。首先创建`FileInputStream`对象,接着创建一个字节数组存储读取的数据,调用`read()`方法将文件内容填充至数组。然后将字节数组转换为字符串并打印,最后关闭输入流。注意,`InputStream`是抽象类,此处使用其子类`FileInputStream`。其他子类如`ByteArrayInputStream`、`ObjectInputStream`和`BufferedInputStream`各有特定用途。
21 2
|
12天前
|
存储 Java Linux
【Java EE】 文件IO的使用以及流操作
【Java EE】 文件IO的使用以及流操作
|
17天前
|
存储 Java 数据库
[Java 基础面试题] IO相关
[Java 基础面试题] IO相关
|
18天前
|
缓存 Java API
Java NIO和IO之间的区别
NIO(New IO),这个库是在JDK1.4中才引入的。NIO和IO有相同的作用和目的,但实现方式不同,NIO主要用到的是块,所以NIO的效率要比IO高很多。在Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO。
16 1
|
10月前
|
Java
Java NIO系列教程三
​ 今天主要给大家介绍的是Buffer的基本使用这个也是NIO里面最总要的概率之一,里面的操作也是有一些复杂的同时也是需要大家必须要重点掌握的知识点,同时也介绍了一下Selector的用法下一篇文章我们将为大家介绍Pipe管道以及FileLock文件锁这也是NIO里面最后的一分部内容了。
81 0
|
10月前
|
安全 Java API
Java NIO系列教程四【完】-管道-文件锁-异步写入
​ 到此位置NIO的所有的内容都结束了,对于NIO来说主要是各种概念需要大家去理解然后有很多的用法和api也需要大家去熟悉所以想把NIO学懂学好其实并不容易一定要多写案例去测试巩固,也预祝大家能把NIO的知识看懂理顺!!!
82 0