java 使用 NIO 读写文件

本文通过示例展示了如何使用Java NIO进行文件的读取和写入操作,包括使用RandomAccessFile和FileChannel进行高效的数据传输,以及ByteBuffer在读写过程中的角色和作用。
    public static void Readnio() {
        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;
        try {
            randomAccessFile = new RandomAccessFile("f:\\a.txt", "rw");		//字符文件
           // randomAccessFile = new RandomAccessFile("f:\\a.jpg", "rw");	//字节文件
            fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = fileChannel.read(byteBuffer);
            while (read != -1) {
                byteBuffer.flip();	// Buffer切换为读取模式
                while (byteBuffer.hasRemaining()) {
                    System.out.println((char) byteBuffer.get());
					WriteNio(String.valueOf((char) byteBuffer.get()), null);	//写入字符
				//	WriteNio(null, buf);			//写入字节
                }
                byteBuffer.compact();      // 清空Buffer区
                read = fileChannel.read(byteBuffer);     // 继续将数据写入缓存区
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
public static void WriteNio(String str, ByteBuffer byteBuffer) {
        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;
        try {
            randomAccessFile = new RandomAccessFile("f:\\b.txt", "rw");		//字符文件
         //  randomAccessFile = new RandomAccessFile("f:\\b.jpg", "rw");	//字节文件
            randomAccessFile.seek(randomAccessFile.length());           //防止覆盖原文件内容
            fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer1 = ByteBuffer.wrap(str.getBytes());
            fileChannel.write(byteBuffer1);	 //写入字符            
         //   fileChannel.write(byteBuffer);	//写入字节

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();

                }
                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值