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();
        }    
    }
相關文章
相關標籤/搜索