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();
        }    
    }
复制代码

 

posted @   温布利往事  阅读(1139)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示