Java NIO中的读和写


阅读目录

  • 一、概述
  • 二、从文件中读取
  • 三、写入文件  
  • 四、读写结合

一、概述

  读和写是I/O的基本过程。从一个通道中读取只需创建一个缓冲区,然后让通道将数据读到这个缓冲区。写入的过程是创建一个缓冲区,用数据填充它,然后让通道用这些数据来执行写入操作。

二、从文件中读取

  1、原始I/O读文件

  如果使用原来的I/O,那么只需要创建一个FileInputStream并从它那里读取,示例代码如下:

public class BioTest
{
    public static void main(String[] args) throws IOException
    {
        FileInputStream in=null;
        try
        {
            in=new FileInputStream("src/main/java/data/nio-data.txt");
            int b;
             while((b=in.read())!=-1)
            {
                //一次读一个字节
                System.out.print((char)b);
            }
        } 
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        
    }
}

  2、NIO读文件

  在NIO系统中,任何时候执行一个读操作,都是从通道中读取,所有的数据最终都是驻留在缓冲区中。读文件涉及三个步骤:

  1. 从FileInPutStream获取Channel
  2. 创建Buffer
  3. 将数据从Channel读到Buffer中

  示例代码如下:

    //读文件
    private static void readFileNio()
    {
        FileInputStream fileInputStream;
        try
        {
            fileInputStream = new FileInputStream("src/main/java/data/nio-data.txt");
            FileChannel fileChannel=fileInputStream.getChannel();//从 FileInputStream 获取通道
            ByteBuffer byteBuffer=ByteBuffer.allocate(1024);//创建缓冲区
            int bytesRead=fileChannel.read(byteBuffer);//将数据读到缓冲区
            while(bytesRead!=-1)
            {
                /*limit=position
                 * position=0;
                 */
                byteBuffer.flip();
                //hasRemaining():告知在当前位置和限制之间是否有元素
                while (byteBuffer.hasRemaining())
                {
                    System.out.print((char) byteBuffer.get());
                }
                /*
                 * 清空缓冲区
                 * position=0;
                 * limit=capacity;
                 */
                byteBuffer.clear();
                bytesRead = fileChannel.read(byteBuffer);
            }
        } catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }    

三、写入文件  

  1、原始I/O写文件

  private static void writeFile()
    {
        FileOutputStream out=null;
        try
        {
            out=new FileOutputStream("src/main/java/data/nio-data.txt");
            out.write("hello".getBytes());
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

  2、NIO写入文件

  //写文件
    private static void writeFileNio()
    {
        try
        {
            RandomAccessFile fout = new RandomAccessFile("src/main/java/data/nio-data.txt", "rw");
            FileChannel fc=fout.getChannel();
            ByteBuffer buffer=ByteBuffer.allocate(1024);
            buffer.put("hi123".getBytes());
            buffer.flip();
            try
            {
                fc.write(buffer);
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } 
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

四、读写结合

  将一个文件的所有内容拷贝到另一个文件中。CopyFile.java 执行三个基本操作:首先创建一个 Buffer,然后从源文件中将数据读到这个缓冲区中,然后将缓冲区写入目标文件。这个程序不断重复 ― 读、写、读、写 ― 直到源文件结束。示例代码如下:

//拷贝文件
    private static void copyFile()
    {
        FileInputStream in=null;
        FileOutputStream out=null;
        try
        {
            in=new FileInputStream("src/main/java/data/in-data.txt");
            out=new FileOutputStream("src/main/java/data/out-data.txt");
            FileChannel inChannel=in.getChannel();
            FileChannel outChannel=out.getChannel();
            ByteBuffer buffer=ByteBuffer.allocate(1024);
            int bytesRead = inChannel.read(buffer);
            while (bytesRead!=-1)
            {
                buffer.flip();
                outChannel.write(buffer);
                buffer.clear();
                bytesRead = inChannel.read(buffer);
            }
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }    
    }

本文永久更新链接地址

相关内容