Java NIO中的读和写

1、概述

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

2、从文件中读取

  一、原始I/O读文件

  若是使用原来的I/O,那么只须要建立一个FileInputStream并从它那里读取,示例代码以下:dom

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();
        }
        
    }
}

  二、NIO读文件

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

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

  示例代码以下:code

    //读文件
    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();
        }
    }    

3、写入文件  

  一、原始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();
        }
    }

  二、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();
        }
    }

4、读写结合

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

//拷贝文件
    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();
        }    
    }
相关文章
相关标签/搜索