原文: https://howtodoinjava.com/java7/nio/3-ways-to-read-files-using-java-nio/

    新的 I/O,通常称为 NIO ,是一组 API,它们为密集的 I/O 操作提供附加能力。 它是由 Sun 微系统的 Java 1.4 发行版引入的,以补充现有的标准 I/O。 随 Java SE 7(“海豚”)一起发布的扩展 NIO 提供了进一步的新文件系统 API,称为 NIO2。

    java 面试 中,与 NIO 相关的问题非常流行。

    NIO2 提供了两种主要的读取文件的方法:

    • 使用缓冲区和通道类
    • 使用路径和文件类

    在这篇文章中,我展示了几种从文件系统读取文件的方法。 因此,让我们从首先展示旧的著名方法入手,以便我们可以看到真正的变化。

    古老的著名 I/O 方式

    此示例说明我们如何使用旧的 I/O 库 API 读取文本文件。 它使用BufferedReader对象进行读取。 另一种方法可以使用InputStream实现。

    1. package com.howtodoinjava.test.nio;
    2. import java.io.BufferedReader;
    3. import java.io.FileReader;
    4. import java.io.IOException;
    5. public class WithoutNIOExample
    6. {
    7. public static void main(String[] args)
    8. {
    9. BufferedReader br = null;
    10. String sCurrentLine = null;
    11. try
    12. {
    13. br = new BufferedReader(
    14. new FileReader("test.txt"));
    15. while ((sCurrentLine = br.readLine()) != null)
    16. {
    17. System.out.println(sCurrentLine);
    18. }
    19. }
    20. catch (IOException e)
    21. {
    22. e.printStackTrace();
    23. }
    24. finally
    25. {
    26. try
    27. {
    28. if (br != null)
    29. br.close();
    30. } catch (IOException ex)
    31. {
    32. ex.printStackTrace();
    33. }
    34. }
    35. }
    36. }

    1)在文件大小的缓冲区中读取一个小文件

    1. package com.howtodoinjava.test.nio;
    2. import java.io.IOException;
    3. import java.io.RandomAccessFile;
    4. import java.nio.ByteBuffer;
    5. import java.nio.channels.FileChannel;
    6. public class ReadFileWithFileSizeBuffer
    7. {
    8. public static void main(String args[])
    9. {
    10. try
    11. {
    12. RandomAccessFile aFile = new RandomAccessFile(
    13. "test.txt","r");
    14. FileChannel inChannel = aFile.getChannel();
    15. long fileSize = inChannel.size();
    16. ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
    17. inChannel.read(buffer);
    18. //buffer.rewind();
    19. buffer.flip();
    20. for (int i = 0; i < fileSize; i++)
    21. {
    22. System.out.print((char) buffer.get());
    23. }
    24. inChannel.close();
    25. aFile.close();
    26. }
    27. catch (IOException exc)
    28. {
    29. System.out.println(exc);
    30. System.exit(1);
    31. }
    32. }
    33. }

    2)使用固定大小的缓冲区分块读取大文件

    package com.howtodoinjava.test.nio;
    
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    
    public class ReadFileWithFixedSizeBuffer 
    {
        public static void main(String[] args) throws IOException 
        {
            RandomAccessFile aFile = new RandomAccessFile
                    ("test.txt", "r");
            FileChannel inChannel = aFile.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while(inChannel.read(buffer) > 0)
            {
                buffer.flip();
                for (int i = 0; i < buffer.limit(); i++)
                {
                    System.out.print((char) buffer.get());
                }
                buffer.clear(); // do something with the data and clear/compact it.
            }
            inChannel.close();
            aFile.close();
        }
    }
    

    3)使用映射的字节缓冲区的更快的文件复制

    package com.howtodoinjava.test.nio;
    
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;
    
    public class ReadFileWithMappedByteBuffer 
    {
        public static void main(String[] args) throws IOException 
        {
            RandomAccessFile aFile = new RandomAccessFile
                    ("test.txt", "r");
            FileChannel inChannel = aFile.getChannel();
            MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
            buffer.load();    
            for (int i = 0; i < buffer.limit(); i++)
            {
                System.out.print((char) buffer.get());
            }
            buffer.clear(); // do something with the data and clear/compact it.
            inChannel.close();
            aFile.close();
        }
    }
    

    所有上述技术将读取文件的内容并将其打印到控制台。 阅读后,您可以做任何您想做的事情。

    祝您学习愉快!