歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java NIO中的讀和寫

Java NIO中的讀和寫

日期:2017/3/1 9:13:50   编辑:Linux編程

閱讀目錄

  • 一、概述
  • 二、從文件中讀取
  • 三、寫入文件  
  • 四、讀寫結合

一、概述

  讀和寫是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();
        }    
    }

Copyright © Linux教程網 All Rights Reserved